package com.kitty.game.role.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kitty.common.cache.RedisService;
import com.kitty.common.db.Db4CommonService;
import com.kitty.common.model.Pos;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.thread.IdGenerator;
import com.kitty.common.core.SchedulerManager;
import com.kitty.cross.CrossServerConfig;
import com.kitty.game.ServerService;
import com.kitty.game.achieve.body.AchieveSet;
import com.kitty.game.activity.message.RespActiviyDataList;
import com.kitty.game.activity.message.vo.Activity;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.ActivityService;
import com.kitty.game.activity.service.shidao.ShiDaoHandler;
import com.kitty.game.activity.service.task.ShuaDaoTaskHandler;
import com.kitty.game.activity.service.vip.SuperVipService;
import com.kitty.game.admin.service.AdminService;
import com.kitty.game.attribute.AttrService;
import com.kitty.game.bag.message.RespFlushPack;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.base.service.BagService;
import com.kitty.game.chat.message.RespChat;
import com.kitty.game.chat.message.RespChatUseCard;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.child.model.ChildInfo;
import com.kitty.game.config.*;
import com.kitty.game.drop.newservice.NewDropService;
import com.kitty.game.drop.service.DropService;
import com.kitty.game.enter.*;
import com.kitty.game.equip.message.RespAchieveFinished;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.equip.service.HDDSService;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.bean.FightObject;
import com.kitty.game.fight.message.ReqFightDoAction;
import com.kitty.game.fight.message.RespAutoFightSkill;
import com.kitty.game.fight.message.RespFightCommandInfo;
import com.kitty.game.fight.message.vo.SkillGroup;
import com.kitty.game.fight.model.SkillAutoPicker;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.fight.service.CountService;
import com.kitty.game.fight.service.FightMessageService;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.fight.util.FightAction;
import com.kitty.game.fly.FlyTypeEnums;
import com.kitty.game.friend.model.Friend;
import com.kitty.game.friend.model.FriendGroup;
import com.kitty.game.function.model.FunctionType;
import com.kitty.game.function.model.RoleFunction;
import com.kitty.game.function.service.FasionService;
import com.kitty.game.gate.LoginAuth;
import com.kitty.game.guard.service.GuardService;
import com.kitty.game.hunpo.service.HunPoService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.i18n.I18nIdDataPool;
import com.kitty.game.identity.IdentityType;
import com.kitty.game.item.service.ChangeCardService;
import com.kitty.game.jiehun.JiehunController;
import com.kitty.game.jiutian.MSGJiuTianRespMasterInfo;
import com.kitty.game.luoshu.Updatejingyan;
import com.kitty.game.mail.model.Mail;
import com.kitty.game.map.service.MapService;
import com.kitty.game.market.MarketService;
import com.kitty.game.neidan.model.NeidanProp;
import com.kitty.game.neidan.service.NeidanService;
import com.kitty.game.newchoujiang.SendPopMessage;
import com.kitty.game.newchoujiang.service.NewChouJiangService;
import com.kitty.game.pay.PayDataPool;
import com.kitty.game.pet.PetDataPool;
import com.kitty.game.pet.bean.PetObject;
import com.kitty.game.pet.message.RespSetCurrentPet;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.player.PlayerService;
import com.kitty.game.player.model.*;
import com.kitty.game.rank.model.monitor.PetAttribMonitor;
import com.kitty.game.rank.model.monitor.RoleAttribMonitor;
import com.kitty.game.role.RoleController;
import com.kitty.game.role.RoleDataPool;
import com.kitty.game.role.RoleEquipInfos;
import com.kitty.game.role.message.*;
import com.kitty.game.role.model.*;
import com.kitty.game.safeLock.service.SafeService;
import com.kitty.game.scene.SceneManager;
import com.kitty.game.server.message.*;
import com.kitty.game.skill.SkillDataPool;
import com.kitty.game.skill.message.RespUpdateSkill;
import com.kitty.game.skill.message.vo.SkillInfo;
import com.kitty.game.skill.model.RoleSkill;
import com.kitty.game.skill.service.SkillService;
import com.kitty.game.statistics.service.StatsService;
import com.kitty.game.system.message.RespSettingInfo;
import com.kitty.game.system.message.vo.SettingInfo;
import com.kitty.game.task.TaskDataPool;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.game.task.service.taskHandler.GodProtectTaskHandler;
import com.kitty.game.task.service.taskHandler.LuobotaoziTaskHandler;
import com.kitty.game.task.service.taskHandler.RechargeScoreTaskHandler;
import com.kitty.game.task.service.taskHandler.TaskHelper;
import com.kitty.game.team.message.*;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.titleManage.entity.TitleDetailInfo;
import com.kitty.game.titleManage.service.TitleInfoService;
import com.kitty.game.tuoguan.TuoguanController;
import com.kitty.game.utils.*;
import com.kitty.game.utils.dirtywords.WordService;
import com.kitty.game.welfare.message.RespOpenWelfare;
import com.kitty.game.welfare.message.RespRechargeInfo;
import com.kitty.game.welfare.service.OnlineRewardHandler;
import com.kitty.game.welfare.service.WelfareService;
import com.kitty.game.wuhun.WuHunPoProp;
import com.kitty.game.wuhun.WuHunService_;
import com.kitty.game.zhenmolu.service.ZhenMoLuService;
import com.kitty.game.zhounian.kuozhan.Resexelua;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.annotation.EventHandler;
import com.kitty.listener.event.*;
import com.kitty.common.model.Reason;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.filter.HeartbeatFilter;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.session.SessionManager;
import com.kitty.mina.session.SessionProperties;
import com.kitty.web.common.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.kitty.common.model.Reason.hdds_buy;


@Service
@Slf4j
public class RoleService {

    @Autowired
    Dao dao;
    @Autowired
    MapService mapService;
    @Autowired
    WuHunService_ WWuHunService;
    @Autowired
    WordService wordService;
    @Autowired
    FightService fightService;
    @Autowired
    FightMessageService fightMessageService;
    @Autowired
    CountService countService;
    @Autowired
    AccountService accountService;
    @Autowired
    PetService petService;
    @Autowired
    ServerService serverService;
    @Autowired
    BroadcastService broadcastService;
    @Autowired
    SkillService skillService;
    @Autowired
    EquipService equipService;
    @Autowired
    FasionService fasionService;
    @Autowired
    BagService bagService;
    @Autowired
    NewTaskService newTaskService;
    @Autowired
    private GateService gateService;
    @Autowired
    private HunPoService hunPoService;
    @Autowired
    HDDSService hddsService;
    @Autowired
    private AdminService adminService ;
    @Autowired
    PayService payService;
    @Autowired
    RedisService redisService;

    @Autowired
    private NeidanService neidanService;

    public ConcurrentHashMap<String, String> wuxing = new ConcurrentHashMap<>();
    /**
     * 角色退出
     */
    @EventHandler(EventType.LOGOUT)
    public void handleLogoutEvent(LogoutEvent logoutEvent) {
        Role role = logoutEvent.getRole();

        /**清除心跳记录*/
        HeartbeatFilter.cleanHeartBeatRecord(role.getUid());

        /**安全密码验证状态设置为未验证*/
        role.setUnlock(false);
//        /**更新角色在线状态*/
        /* 在线状态*/
        role.setOn_line(0);
        //alterOnlineStatus(role.getUid(), false, "不在线");

        /**下线时，把当次登录时间加到之前的在线时长中*/
        role.setPreOnlineSec(getOnlineSec(role));

        role.save();
    }

    /**
     * 登录事件
     */
    @EventHandler(EventType.LOGIN)
    public void handleLoginEvent(LoginEvent loginEvent) {

        Role role = loginEvent.getRole();

        /**修复一下属性点跟相性点*/
        role.setLastAttrib(getLastAttributePoint(role));
        role.setLastPolar(getLastPolarPoint(role));
        sendExtraAttribute(role);
        BossImgInfos bossImgInfos = role.getExtendBox().getBossImgInfos();
        if(bossImgInfos == null){
            bossImgInfos = new BossImgInfos();
            role.getExtendBox().setBossImgInfos(bossImgInfos);
        }

        /**清除心跳记录*/
        HeartbeatFilter.cleanHeartBeatRecord(role.getUid());
        /** 登录的时候检查重置 */
        checkReset(role);

//        /**所在线路名称在线状态*/
        //  alterOnlineStatus(role.getUid(), true, serverService.getServer().getSonName());
//
        /**发送自动战斗的状态*/
        sendAutoSet(role);

        /**发送刷道道具的状态*/
        sendShuadaoStauts(role);

        /**发送到登录服*/
        gateService.addRoleToDist(role.getSid(), new PlayerProfile(role));

        /**弹出离线的提示信息*/
        popOfflineNotice(role);
    }

    /**
     * 处理角色升级事件
     */
    @EventHandler(EventType.ROLE_LEVEL_UP)
    public void handleRoleLevelUpEvent(RoleLevelUpEvent roleLevelUpEvent) {
        Role role = roleLevelUpEvent.getRole();
        if (role == null) {
            return;
        } else {
            if (role.getLevel() == 75) {
                addRechargeScore(role, 20);
            } else if (role.getLevel() == 80) {
                addRechargeScore(role, 20);
            } else if (role.getLevel() == 90) {
                addRechargeScore(role, 50);
            } else if (role.getLevel() == 100) {
                addRechargeScore(role, 80);
            } else if (role.getLevel() == 110) {
                addRechargeScore(role, 130);
            } else if (role.getLevel() == 120) {
                addRechargeScore(role, 150);
            } else if (role.getLevel() == 130) {
                addRechargeScore(role, 150);
            }
        }

    }

    public int getRoleId() {
        return SpringUtils.getIdentityService().getNextId(IdentityType.ROLE);
    }

    /**
     * 新手上线赠送宝宝和装备
     */
    public void giftPetAndEquip(Role role) {
        equipService.getNewcomerEquip(role, (short) 2, 2);
        equipService.getNewcomerEquip(role, (short) 3, 3);
        equipService.getNewcomerEquip(role, (short) 10, 10);
    }

    /**
     * 更新角色鉴定进度
     */
    public void updateIdentify(Role role) {
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(Collections.singletonList(new FiedValue(200, role.getEquipIdentify())));
        MessagePusher.pushMessage(role, respUpdate);
    }

    /**
     * 更新洛书
     */
    public void updateluoshuExp(Role role) {
        Updatejingyan updateJingyan = new Updatejingyan();
        ArrayList<FiedValue> fiedValues = new ArrayList();
        fiedValues.add(new FiedValue(25, 3, role.getLuoshuExp()));
        updateJingyan.setList(fiedValues);
        role.save();
        MessagePusher.pushMessage(role, updateJingyan);
    }

    /**
     * 更新角色金钱
     */
    public void updateRoleMoney(Role role) {
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(27, role.getMoney()));
        list.add(new FiedValue(309, role.getVoucher()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
    }

    /**
     * 更新存款
     */
    public void updateSaveMoney(Role role) {
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(Collections.singletonList(new FiedValue(28, role.getStoreMoney())));
        MessagePusher.pushMessage(role, respUpdate);
    }

    /**
     * 更新角色潜能
     */
    public void updateRolePot(Role role) {
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(Collections.singletonList(new FiedValue(26, role.getPot())));
        MessagePusher.pushMessage(role, respUpdate);
    }

    /**
     * 更新角色元宝数量
     */
    public void updateRoleGoldAndSiver(Role role) {
        Account account = SpringUtils.getAccountService().getAccount(role.getSid());
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(119, role.getSiver()));
        list.add(new FiedValue(120, account.getGold()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
    }

    /**
     * 奖励提示组合
     */
    public void addRewardTips(Role role, String tips, boolean isPet) {
        StringBuilder totalTips;
        if (isPet) {
            totalTips = role.getTempCache(Const.REWARD_PET_TIPS, null);
        } else {
            totalTips = role.getTempCache(Const.REWARD_ROLE_TIPS, null);
        }
        if (totalTips == null) {
            /**添加第一个提示的时候准备定时的提示*/
            Runnable task = role.getTempCache("rewardTips", null);
            if (task == null) {
                task = () -> sendRewardTips(role);
                role.pushTempCache("rewardTips", task);
                SchedulerManager.getInstance().schedule(task, 500);
            }

            totalTips = new StringBuilder();
            if (isPet) {
                totalTips.append("你的宠物获得了");
                role.pushTempCache(Const.REWARD_PET_TIPS, totalTips);
            } else {
                totalTips.append("你获得了");
                role.pushTempCache(Const.REWARD_ROLE_TIPS, totalTips);
            }
        }
        if (isPet) {
            if (totalTips.length() > 7) {
                totalTips.append("、");
            }
        } else {
            if (totalTips.length() > 4) {
                totalTips.append("、");
            }
        }
        totalTips.append(tips);
    }

    /**
     * 取出战斗获得奖励
     */
    public void sendRewardTips(Role role) {
        role.popTempCache("rewardTips");
        String result = "";
        StringBuilder totalTips = role.popTempCache(Const.REWARD_ROLE_TIPS);
        if (totalTips != null && totalTips.length() > 4) {
            result += totalTips.toString();
        }
        totalTips = role.popTempCache(Const.REWARD_PET_TIPS);
        if (totalTips != null && totalTips.length() > 7) {
            if (!Strings.isEmpty(result)) {
                result += "，";
            }
            result += totalTips.toString();
        }

        if (!Strings.isEmpty(result)) {
            result += "。";
            MessagePusher.pushMessage(role, new RespMsg(result));
        }
    }

    /**
     * 扣除金钱
     */
    public void subtractMoney(Role role, int money) {
        if (money <= 0) {
            return;
        }
        subtractMoney(role,money,Reason.BUY_ITEM);
    }

    /**
     * 获得金钱
     */
    public void addMoney(Role role, int money) {
        if (money <= 0) {
            return;
        }
        addMoney(role,money, Reason.BUY_ITEM);
    }
    /**
     * 洛书经验
     */

    public void addluoshuExp(Role role, int exp) {
        if (exp > 0) {
            int before = role.getLuoshuExp();
            int addexp = exp;
            exp += before;
            if (exp > 0) {
                role.setLuoshuExp(exp);
                this.updateluoshuExp(role);
                role.save();
                String tips = AsktaoUtil.getMoneyFormat(addexp) + "洛书经验";
                this.addRewardTips(role, tips, false);
                MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));
            }

        }
    }

    /**
     * 增加游戏币
     */
    public void addMoney(Role role, int money, Reason reason) {
        if (money <= 0) {
            return;
        }
        int before = role.getMoney();
        role.addMoney(money, reason);
        role.save();
        int addMoney = role.getMoney() - before;
        if (addMoney > 0) {
            updateRoleMoney(role);

//            RespSyncMessage respSyncMessage = new RespSyncMessage();
//            respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
            String tips = AsktaoUtil.getMoneyFormat(addMoney) + "文金钱";
            addRewardTips(role, tips, false);
//            respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你获得了" + tips + "。")));
            MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));
        }
    }

    /**
     * 扣除游戏币
     */
    public void subtractMoney(Role role, int money, Reason reason) {
        if (money <= 0) {
            return;
        }
        role.costMoney(money, reason);
        role.save();
        updateRoleMoney(role);
    }

    /**
     * 扣除代金券
     */
    public void subtractVoucher(Role role, int voucher) {
        if (voucher <= 0) {
            return;
        }

        role.setVoucher(role.getVoucher() - voucher);
        updateRoleMoney(role);
    }

    public void addFightMatiral(Role role, int matiral) {
        Pet pet = SpringUtils.getPetService().getPetById(role.getPetBox().getFightPetId(), role);
        if (pet == null) {
            return;
        }

        addPetMatiral(role, pet, matiral);
    }

    /**
     * 获得宠物武学
     */
    public void addPetMatiral(Role role, Pet pet, int matiral) {
        if (pet == null) {
            return;
        }

        if (matiral <= 0) {
            return;
        }
        /**增加宠物总武学*/
        addPetTotalMatiral(role, pet, matiral);
        /**增加宠物月武学*/
        addPetMonthMatiral(role, pet, matiral);
    }

    public int getWuxue(int matiral, Pet pet) {
        matiral = matiral * 3;
        matiral = caculatePetMatiral(pet.getLevel(), pet.getMartial(), matiral);
        return matiral;
    }

    /**
     * 增加宠物总武学
     */
    private void addPetTotalMatiral(Role role, Pet pet, int matiral) {
        if (matiral <= 0) {
            return;
        }
        int oldMatiral = pet.getMartial();
        matiral = getWuxue(matiral, pet);
        int total = pet.getMartial() + matiral;
        if (total >= Const.MAX_PET_WUXUE) {
            total = Const.MAX_PET_WUXUE;
        } else if (total < 0) {
            total = Const.INIT_PET_WUXUE;
        }
        pet.setMartial(total);
        role.save();
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(62, pet.getMartial()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(pet.getId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);

//        RespSyncMessage respSyncMessage = new RespSyncMessage();
//        respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
        String tips = "#R" + matiral + "#n点武学";
        addRewardTips(role, tips, true);
//        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你的#Y" + pet.getName() + "#n获得了" + tips + "。")));
        MessagePusher.pushMessage(role, new RespNotifyMisc("你的#Y" + pet.getName() + "#n获得了" + tips + "。"));

        if (pet.getMartial() != oldMatiral) {
            /**产生一个宠物武学变化事件*/
            EventDispatcher.getInstance().fireEvent(new PetMartialChangeEvent(EventType.PET_MARTIAL_CHANGE, role, pet, pet.getMartial()));
        }
    }

    /**
     * 增加宠物月武学
     */
    private void addPetMonthMatiral(Role role, Pet pet, int matiral) {
        if (matiral <= 0) {
            return;
        }
        int oldMonthMatiral = pet.getMonthMartial();
        matiral = caculatePetMatiral(pet.getLevel(), pet.getMonthMartial(), matiral);
        int total = pet.getMartial() + matiral;
        if (total >= Const.MAX_PET_WUXUE) {
            total = Const.MAX_PET_WUXUE;
        } else if (total < 0) {
            total = Const.INIT_PET_WUXUE;
        }
        pet.setMonthMartial(total);
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(466, pet.getMonthMartial()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(pet.getId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
        role.save();

        if (pet.getMonthMartial() != oldMonthMatiral) {
            /**产生一个宠物月武学变化事件*/
            EventDispatcher.getInstance().fireEvent(new PetMonthMartialChangeEvent(EventType.PET_MONTH_MARTIAL_CHANGE, role, pet, pet.getMonthMartial()));
        }
    }

    /**
     * 获得道行
     *
     * @param role
     * @param tao
     */
    public void addTao(Role role, int tao) {
        if (tao <= 0) {
            return;
        }
        /**增加总道行*/
        addTotalTao(role, tao);
        /**增加月道行*/
        addMonthTao(role, tao);
        /**
         * 刷新双倍属性
         */
        refreshRoleBasic(role);
    }

    public int getTao(int tao, Role role) {
        tao = tao / 10 * 5;
        Map.Entry<Integer, String> entryaa = null;
        for (Map.Entry<Integer, String> entry : PayDataPool.ACCUMULATIVE_PAY_TITLES.entrySet()) {
            if (role.getTotalCharge() < entry.getKey()) {
                continue;
            }
            if (entryaa == null) {
                entryaa = entry;
            } else if (entryaa.getKey() < entry.getKey()) {
                entryaa = entry;
            }
        }
        if (entryaa != null) {
//            if (entryaa.getValue().equals("一掷千金")) {
//                tao = tao * 110 / 100;
//            }
//            if (entryaa.getValue().equals("钱乃身外之物")) {
//                tao = tao * 115 / 100;
//            }
//            if (entryaa.getValue().equals("万元户")) {
//                tao = tao * 120 / 100;
//            }
//            if (entryaa.getValue().equals("富甲天下")) {
//                tao = tao * 125 / 100;
//            }
//            if (entryaa.getValue().equals("壕无人性")) {
//                tao = tao * 130 / 100;
//            }
//            if (entryaa.getValue().equals("还有谁")) {
//                tao = tao * 140 / 100;
//            }
        }
        tao = calulateTaoPoint(role.getLevel(), role.getTao(), tao);
        return tao;
    }

    /**
     * 增加总道行
     */
    private void addTotalTao(Role role, int tao) {
        if (tao <= 0) {
            return;
        }
        // 1#202010211137#202010211137#2
        String content = hddsService.getDaohangRate().getData();
        if (content.startsWith("1")) {
            String[] strings = content.split("##");
            Date start = TimeUtil.parse(strings[1], "yyyyMMddHHmm");
            Date end = TimeUtil.parse(strings[2], "yyyyMMddHHmm");
            int rate = Integer.parseInt(strings[3]);
            Date date = new Date();
            if (date.after(start) && date.before(end)) {
                tao = tao * rate;
                log.error("多倍道行=={}", rate);
            }
        }

        /**取出当前的道行点数*/
        long oldTaoPoint = role.getTaoPoint();
        /**递减计算本次获得的点数*/
        tao = getTao(tao, role);//calulateTaoPoint(role.getLevel(), role.getTao(), tao);
        //限制单次 获得道行上限
        int reward_tao = Integer.parseInt(DataCache.REDIS_DATA.get("limit_tao"));
        int limitTao = reward_tao * 360 * 1300;
        if(tao>limitTao){
            tao = limitTao;
        }
        /**总的点数*/
        long total = role.getTaoPoint() + tao;

        if (total >= Const.MAX_DAOHANG) {
            total = Const.MAX_DAOHANG;
        } else if (total < 0) {
            total = Const.INIT_DAOHANG;
        }
        List<FiedValue> list = new ArrayList<>();
        role.setTaoPoint(total);
        role.save();
        list.add(new FiedValue(20, role.getTao()));
        list.add(new FiedValue(175, role.getTaoLastPoint()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
//        RespSyncMessage respSyncMessage = new RespSyncMessage();
//        respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
        String tips = AsktaoUtil.getFormatTao(tao) + "道行";
        addRewardTips(role, tips, false);
//        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你获得了" + tips + "。")));
//        MessagePusher.pushMessage(role, respSyncMessage);
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了" + tips + "。"));

        if (role.getTaoPoint() != oldTaoPoint) {
            /**产生一个道行变化事件*/
            EventDispatcher.getInstance().fireEvent(new TaoChangeEvent(EventType.TAO_CHANGE, role, role.getTao(), role.getTaoPoint() - oldTaoPoint));
        }
    }

    /**
     * 增加总道行
     */
    public void addTotalTao11111(Role role, int tao) {
        if (tao <= 0) {
            return;
        }
        // 1#202010211137#202010211137#2
        String content = hddsService.getDaohangRate().getData();
        if (content.startsWith("1")) {
            String[] strings = content.split("##");
            Date start = TimeUtil.parse(strings[1], "yyyyMMddHHmm");
            Date end = TimeUtil.parse(strings[2], "yyyyMMddHHmm");
            int rate = Integer.parseInt(strings[3]);
            Date date = new Date();
            if (date.after(start) && date.before(end)) {
                tao = tao * rate;
                log.error("多倍道行=={}", rate);
            }
        }
        //限制单次 获得道行上限
        int reward_tao = Integer.parseInt(DataCache.REDIS_DATA.get("limit_tao"));
        int limitTao = reward_tao * 360 * 1300;
        if(tao>limitTao){
            tao = limitTao;
        }
        /**取出当前的道行点数*/
        long oldTaoPoint = role.getTaoPoint();
//        log.error("为衰减的道行=={}",tao);
        /**总的点数*/
        long total = role.getTaoPoint() + tao;

        if (total >= Const.MAX_DAOHANG) {
            total = Const.MAX_DAOHANG;
        } else if (total < 0) {
            total = Const.INIT_DAOHANG;
        }
        List<FiedValue> list = new ArrayList<>();
        role.setTaoPoint(total);
        role.save();
        list.add(new FiedValue(20, role.getTao()));
        list.add(new FiedValue(175, role.getTaoLastPoint()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
        log.error("增加总道行=={}=={}=={}=={}", role.getRoleId(), role.getName(), role.getTaoPoint(), tao);
//        RespSyncMessage respSyncMessage = new RespSyncMessage();
//        respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
        String tips = AsktaoUtil.getFormatTao(tao) + "道行";
        addRewardTips(role, tips, false);
//        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你获得了" + tips + "。")));
        MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));

        if (role.getTaoPoint() != oldTaoPoint) {
            /**产生一个道行变化事件*/
            EventDispatcher.getInstance().fireEvent(new TaoChangeEvent(EventType.TAO_CHANGE, role, role.getTao(), role.getTaoPoint() - oldTaoPoint));
        }
    }

    //    /**
//     * 增加月道行
//     */
    public void addMonthTao(Role role, int resultTao) {
        if (resultTao <= 0) {
            return;
        }
        long oldMonthTaoPoint = role.getMonthTaoPoint();
        resultTao = calulateTaoPoint(role.getLevel(), (int) oldMonthTaoPoint, resultTao);
        long total = oldMonthTaoPoint + resultTao;
        log.error("增加月道行=={}=={}=={}=={}", role.getRoleId(), role.getName(), role.getMonthTaoPoint(), resultTao);
        if (total >= Const.MAX_DAOHANG) {
            total = Const.MAX_DAOHANG;
        } else if (total < 0) {
            total = Const.INIT_DAOHANG;
        }
        role.setMonthTaoPoint(total);
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(462, role.getMonthTao()));
        list.add(new FiedValue(463, role.getMonthTaoLastPoint()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
        role.save();
        String tips = AsktaoUtil.getFormatTao(resultTao) + "月道行";
        MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));
        if (role.getMonthTaoPoint() != oldMonthTaoPoint) {
            /**产生一个月道行变化事件*/
            EventDispatcher.getInstance().fireEvent(new MonthTaoChangeEvent(EventType.MONTH_TAO_CHANGE, role, role.getMonthTao(), role.getMonthTaoPoint() - oldMonthTaoPoint));
        }
    }

    public void addMonthTao11111(Role role, int resultTao) {
        if (resultTao <= 0) {
            return;
        }
        long oldMonthTaoPoint = role.getMonthTaoPoint();
        long total = role.getMonthTaoPoint() + resultTao;
        log.error("增加月道行=={}=={}=={}=={}", role.getRoleId(), role.getName(), role.getMonthTaoPoint(), resultTao);
        if (total >= Const.MAX_DAOHANG) {
            total = Const.MAX_DAOHANG;
        } else if (total < 0) {
            total = Const.INIT_DAOHANG;
        }
        role.setMonthTaoPoint(total);
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(462, role.getMonthTao()));
        list.add(new FiedValue(463, role.getMonthTaoLastPoint()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
        role.save();
        String tips = AsktaoUtil.getFormatTao(resultTao) + "月道行";
        MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));
        if (role.getMonthTaoPoint() != oldMonthTaoPoint) {
            /**产生一个月道行变化事件*/
            EventDispatcher.getInstance().fireEvent(new MonthTaoChangeEvent(EventType.MONTH_TAO_CHANGE, role, role.getMonthTao(), role.getMonthTaoPoint() - oldMonthTaoPoint));
        }
    }

    /**
     * 传入要加的道行值和已拥有道行值计算出实际可以加的道行值
     * 返回道行点数 外面再根据需要获得 年 天 点
     */
    private int calulateTaoPoint(int level, int ownTao, int addTao) {
        double stdTao = FormulaUtil.getStdTao(level);
        int divTao = (int) (stdTao * 2 + ownTao);
        if (divTao == 0) {
            divTao = 1;
        }
        int result = (int) (Arith.div(Arith.mul(addTao, stdTao), divTao) * Const.ONE_DAY_POINT);
        if (result <= 0) {
            result = 1;
        }
        return result;
    }

    /**
     * 传入要加的武学值和已拥有武学值计算出实际可以加的武学值
     */
    private int caculatePetMatiral(int petLevel, int ownPetMatiral, int addMatiral) {
        int stdMatiral = FormulaUtil.getStdMartial(petLevel);
        int divMatiral = stdMatiral + ownPetMatiral;
        if (divMatiral <= 0) {
            divMatiral = 1;
        }
        return (int) Arith.div(Arith.mul(addMatiral, stdMatiral), divMatiral);
    }

    /**
     * 添加潜能
     */
    public void addPot(Role role, int pot) {
        if (pot <= 0) {
            return;
        }
        pot = pot * 1;
        long total = role.getPot() + pot;
        if (total >= 2000000000) {
            total = 2000000000;
        } else if (total < 0) {
            total = 0;
        }
//        RespSyncMessage respSyncMessage = new RespSyncMessage();
//        respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
        String tips = "#R" + pot + "#n点潜能";
        addRewardTips(role, tips, false);
//        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你获得了" + tips + "。")));
        MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));
        role.setPot((int) total);
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(26, 3, role.getPot()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);

        /**产生一个潜能变化事件*/
        EventDispatcher.getInstance().fireEvent(new PotChangeEvent(EventType.POT_CHANGE, role, role.getPot(), pot));
    }

    /**
     * 获取经验
     *
     * @param role
     * @param exp
     */
    public void addExp(Role role, int exp, int monsterLevel, int currPetId) {
        if (exp <= 0) {
            return;
        }
        // 1#202010211137#202010211137#2
        String content = hddsService.getExpRate().getData();
        if (content.startsWith("1")) {
            String[] strings = content.split("##");
            Date start = TimeUtil.parse(strings[1], "yyyyMMddHHmm");
            Date end = TimeUtil.parse(strings[2], "yyyyMMddHHmm");
            int rate = Integer.parseInt(strings[3]);
            Date date = new Date();
            if (date.after(start) && date.before(end)) {
                exp = exp * rate;
                log.error("多倍经验=={}", rate);
            }
        }
        refreshRoleBasic(role);
        short maxLevel;
        long needExp=0;
        long totalExp=0;
        short oldLevel, level;
        ChildInfo childInfo = role.getChildInfo();
        int maxLv = Integer.parseInt(DataCache.REDIS_DATA.get("role_max_lv"));
        if (role.isRealBody()) {
            maxLevel = (short)maxLv;// 人物最高等级
            needExp = getRoleUpgradeNeedExp(role.getLevel());
            totalExp = (long)role.getExp() + (long)exp;
            oldLevel = role.getLevel();
            level = role.getLevel();
        } else {
            maxLevel = 139;// 应该是元婴最高等级
            needExp = childInfo.getUpgradeExp();
            totalExp = (long)childInfo.getExp() + (long)exp;
            oldLevel = childInfo.getLevel();
            level = childInfo.getLevel();
        }
        // 人物获得经验
        int petExp = exp;
        if (level < maxLevel) {
            if (role.isLockexp()) {
//                RespSyncMessage respSyncMessage = new RespSyncMessage();
//                respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
//                respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("由于你锁定了经验，无法获得经验。")));
//                MessagePusher.pushMessage(role, respSyncMessage);
                MessagePusher.pushMessage(role, new RespNotifyMisc("由于你锁定了经验，无法获得经验。"));
            } else if (childInfo.getType() == 0 && role.getLevel() >= Const.MAX_LEVEL_NO_CHILD) {
                /**未飞升时等级达到115级，提示需要飞升信息*/
                MessagePusher.notify2Player(role, I18nId.PMT_2302);
            } else if (totalExp >= needExp) {
                // mod tao 循环升级
                while (totalExp >= needExp) {
                    RoleAttribMonitor roleAttribMonitor = new RoleAttribMonitor(role);
                    int lastExp = (int) (totalExp - needExp);
                    level = (short) (level + 1);
                    if (role.isRealBody()) {
                        role.setLevel(level);
                        if (level == 80) {
                            role.setLuoshuMagpower(105);
                            role.setLuoshumPhypower(190);
                            role.setExtraPhyPower(role.getExtraPhyPower() + 190);
                            role.setExtraMagPower(role.getExtraMagPower() + 105);
                            SpringUtils.getRoleService().sendExtraAttribute(role);
                            role.save();
                            RespMsg respInviteMsg = new RespMsg();
                            respInviteMsg.setMsg("洛书系统已开启！");
                            MessagePusher.pushMessage(role, respInviteMsg);
                            Collection<Pet> pets = role.getPetBox().getAllPets().values();
                            for (Pet pet : pets) {
                                this.petService.refreshPetInfo(role, pet);
                            }
                        }
                        role.setExp(lastExp);
                    } else {
                        if(level == 120){
                            //升级到120的时候判断真身的状态  是元婴还是血婴，如 是 则自动飞升。
                            if(childInfo.getState() == 1 || childInfo.getState() == 2){
                                if(childInfo.getType() == 1){
                                    role.getChildInfo().setType((byte)3);
                                }
                                if(childInfo.getType() == 2){
                                    role.getChildInfo().setType((byte)4);
                                }
                                MessagePusher.pushMessage(role, new RespNotifyMiscEx("元婴/血婴等级达到120级，自动飞升已完成！"));
                            }
                        }
                        childInfo.setLevel(level);
                        childInfo.setExp(lastExp);
                        List<FiedValue> list = new ArrayList<>();
                        list.add(new FiedValue(345, childInfo.getMaxPolarExtra()));//upgrade/max_polar_extra  元婴增加的相性上限 每7级增加一点
                        RespUpdate respUpdate = new RespUpdate();
                        respUpdate.setRoleId(role.getRoleId());
                        respUpdate.setList(list);
                        MessagePusher.pushMessage(role, respUpdate);
                    }
                    if (level >= maxLevel) {
                        level = maxLevel;
                        if (role.isRealBody()) {
                            role.setExp(0);
                        } else {
                            childInfo.setExp(0);
                        }
                    }
                    role.setLastAttrib(getLastAttributePoint(role));
                    role.setLastPolar(getLastPolarPoint(role));
                    role.setBasicAttrib();
                    role.setCurrLife(role.getMaxLife());
                    role.setCurrMana(role.getMaxMana());
                    autoAddPoint(role, null);
                    autoPolar(role);
                    if (role.isRealBody()) {
                        this.gateService.addRoleToDist(role.getSid(), new PlayerProfile(role));
                        SpringUtils.getBean(GuardService.class).loadGuard(role);
                        EventDispatcher.getInstance().fireEvent(new RoleLevelUpEvent(EventType.ROLE_LEVEL_UP, role, oldLevel, role.getLevel()));
                    } else {
                        EventDispatcher.getInstance().fireEvent(new ChildLevelUpEvent(EventType.CHILD_LEVEL_UP, role, oldLevel, childInfo.getLevel()));
                    }
                    sendExtraAttribute(role);
                    // add tao 更新经验条
                    List<FiedValue> list = new ArrayList<>();
                    if (role.isRealBody()) {
                        list.add(new FiedValue(25, 3, Integer.valueOf(role.getExp())));
                        list.add(new FiedValue(55, 3, Long.valueOf(getRoleUpgradeNeedExp(role.getLevel()))));
                    } else {
                        list.add(new FiedValue(343, 3, Integer.valueOf(childInfo.getExp())));
                        list.add(new FiedValue(344, 3, Long.valueOf(childInfo.getUpgradeExp())));
                    }
                    RespUpdate respUpdate = new RespUpdate();
                    respUpdate.setRoleId(role.getRoleId());
                    respUpdate.setList(list);
                    MessagePusher.pushMessage(role, respUpdate);
                    // add:e
                    SceneManager.INSTANCE.sendMessages(role, new RespLevelUp(role.getRoleId(), role.getLevel()));
                    roleAttribMonitor.end();
                    EventDispatcher.getInstance().fireEvent(new RoleExpChangeEvent(EventType.ROLE_EXP_CHANGE, role, exp));
                    // add tao
                    if(role.isRealBody()){
                        needExp = getRoleUpgradeNeedExp(role.getLevel());
                    }else {
                        needExp=getRoleFlyUpNeedExp(childInfo.getLevel());
                    }
                    totalExp = lastExp;
                    // add:e
                }
                String tips = "#R" + exp + "#n点经验";
                addRewardTips(role, tips, false);
                MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你升到#R" + level + "#n级了。"));
                // mod:e
            } else {
                // 经验不够升级 添加进去

                if (totalExp > 2000000000) {
                    totalExp = 2000000000;
                } else if (totalExp < 0) {
                    totalExp = 0;
                }
                if (role.isRealBody()) {
                    role.setExp((int) totalExp);
                } else {
                    childInfo.setExp((int) totalExp);
                }

                {
//                    RespSyncMessage respSyncMessage = new RespSyncMessage();
//                    respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
                    String tips = "#R" + exp + "#n点经验";
                    addRewardTips(role, tips, false);
//                    respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你获得了" + tips + "。")));
//                    MessagePusher.pushMessage(role, respSyncMessage);
                    MessagePusher.pushMessage(role, new RespNotifyMisc("你获得了" + tips + "。"));
                }
                log.error("获得经验的角色=={}", role.getName());
                List<FiedValue> list = new ArrayList<>();
                if (role.isRealBody()) {
                    list.add(new FiedValue(25, 3, role.getExp()));
                    list.add(new FiedValue(55, 3, getRoleUpgradeNeedExp(role.getLevel())));
                } else {
                    list.add(new FiedValue(343, 3, childInfo.getExp()));
                    list.add(new FiedValue(344, 3, childInfo.getUpgradeExp()));
                }

                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(role, respUpdate);

                /**产生一个人物经验变化事件*/
                EventDispatcher.getInstance().fireEvent(new RoleExpChangeEvent(EventType.ROLE_EXP_CHANGE, role, exp));
            }
        }

        // 参战宠物获得经验
//        petExp = petExp / 2;
        if (currPetId > 0) {
            Pet pet = SpringUtils.getPetService().getPetById(currPetId, role);
            if (pet != null) {
                if (pet.getLevel() >= role.getLevel() + 15) {//宠物最多比人物高15级
//                    RespSyncMessage respSyncMessage = new RespSyncMessage();
//                    respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
//                    respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("由于#Y" + pet.getNickname() + "#n等级已达到人物携带最大等级，无法获得经验。")));
                    MessagePusher.pushMessage(role, new RespNotifyMisc("由于#Y" + pet.getNickname() + "#n等级已达到人物携带最大等级，无法获得经验。"));
                } else {
                    addPetExp(role, currPetId, petExp, true);
                }
                pet.setIntimacy(pet.getIntimacy() + 1);
            }
        }

        role.save();
    }

    /**
     * 取剩余可分配属性点
     */
    public short getLastAttributePoint(Object object) {
        short last = 0;
        if (object instanceof Role) {
            Role role = (Role) object;
            int total = getTotalPoint(role.getLevel(), true) + getChildAttribPoint(role) + getNeiDanAttribPoint(role); //Todo 这里应该可以加上 飞升增加的属性点  还要加上内丹增加的属性点，
            /**用总可分配属性减去已加属性点*/
//            log.error("=={}=={}=={}=={}=={}=={}",total,role.getCon(),role.getStr(),role.getWiz(),role.getDex());
            last = (short) (total - (role.getCon() + role.getStr() + role.getWiz() + role.getDex()));
        } else if (object instanceof Pet) {
            Pet pet = (Pet) object;
            int total = getTotalPoint(pet.getLevel(), true);
            total += pet.getAddattrNumber();
            /**用总可分配属性减去已加属性点*/
            last = (short) (total - (pet.getCon() + pet.getStr() + pet.getWiz() + pet.getDex()));
        }
        return last;
    }
    /**
     * 返回内丹增加属性
     */
    public int getNeiDanAttribPoint(Role role){
        int num = 0;
        NeidanProp neidanProp = role.getExtendBox().getNeidanProp();
        if(neidanProp != null){
            num =neidanProp.getTotalAttribPoint();
        }
        return num;
    }
    /**
     * 返回内丹增加相性
     */
    public short getNeiDanPolarPoint(Role role){
        short num = 0;
        NeidanProp neidanProp = role.getExtendBox().getNeidanProp();
        if(neidanProp != null){
            num =(short)neidanProp.getTotalPolarPoint();
        }
        return num;
    }
    /**
     * 返回元婴升级增加的属性点数
     */
    public short getChildAttribPoint(Role role) {
        ChildInfo childInfo = role.getChildInfo();
        if (role.getLevel() < 110) {
            return 0;
        }
        return (short) ((childInfo.getLevel() / 10) * 2);
    }

    /**
     * 根据等级返回总属性点抗性点或者相性
     */
    public short getTotalPoint(short level, boolean isAttrib) {
        if (isAttrib) { // 【重要】修复1级宠物的未分配点为0的bug
//            return (short) ((level - 1) * 4);
            return (short) (level * 4);
        } else {
            if (level < 61) {
                return (short) Math.floor(level * 0.5);
            } else {
                return (short) (level - 30);
            }
        }
    }

    /**
     * 取剩余可分配相性点 宠物取剩余抗性点
     */
    public short getLastPolarPoint(Object object) {
        short last = 0;
        int total;
        if (object instanceof Role) {
            Role obj = (Role) object;
            //修复内丹不加相性点问题
            int sum = getTotalPoint(obj.getLevel(), false) +getNeiDanPolarPoint(obj);
            total = (short)sum;
            last = (short) (total - (obj.getMetal() + obj.getEarth() + obj.getWood() + obj.getWater() + obj.getFire()));
        } else if (object instanceof Pet) {
            Pet obj = (Pet) object;
            total = getTotalPoint(obj.getLevel(), false);
            total = total+ obj.getAddattrNumber();
            last = (short) (total - obj.getResistMetal() - obj.getResistWood() - obj.getResistFire() - obj.getResistWater()
                    - obj.getResistEarth() - obj.getResistForgotten() - obj.getResistPoison()
                    - obj.getResistFrozen() - obj.getResistConfusion() - obj.getResistSleep());
        }
        return last;
    }

    /**
     * 自动加点
     */
    public void autoAddPoint(Role role, Pet pet) {
        if (role != null) {
            Map<String, Byte> nutMap = role.getExtendBox().getAutoAttrib();
            if (nutMap.get("status") == 1) {// 开启
                RoleAttribMonitor roleAttribMonitor = new RoleAttribMonitor(role);
                int con = nutMap.get("con");
                int str = nutMap.get("str");
                int dex = nutMap.get("dex");
                int wiz = nutMap.get("wiz");
                if (nutMap.get("type") == Const.ATTRIB_TYPE_PHYCIAL) {// 高物伤 3力1敏
                    while (role.getLastAttrib() >= 4) {
                        role.setStr((short) (role.getStr() + 3));
                        role.setDex((short) (role.getDex() + 1));
                        role.setLastAttrib(getLastAttributePoint(role));
                    }
                } else if (nutMap.get("type") == Const.ATTRIB_TYPE_MAGIC) {// 高法伤 3灵1敏
                    while (role.getLastAttrib() >= 4) {
                        role.setWiz((short) (role.getWiz() + 3));
                        role.setDex((short) (role.getDex() + 1));
                        role.setLastAttrib(getLastAttributePoint(role));
                    }
                } else {// 自定义
                    while (role.getLastAttrib() >= 4) {
                        role.setStr((short) (role.getStr() + str));
                        role.setWiz((short) (role.getWiz() + wiz));
                        role.setDex((short) (role.getDex() + dex));
                        role.setCon((short) (role.getCon() + con));
                        role.setLastAttrib(getLastAttributePoint(role));
                    }
                }

                roleAttribMonitor.end();
            }

            sendExtraAttribute(role);
        }
        if (pet != null) {
            PetAttribMonitor petAttribMonitor = new PetAttribMonitor(role, pet);

            Map<String, Byte> nutMap = pet.getAutoAtrrib();
            if (nutMap.get("status") == 1) {// 开启
                byte con = nutMap.getOrDefault("con", (byte) 0);
                byte str = nutMap.getOrDefault("str", (byte) 0);
                byte dex = nutMap.getOrDefault("dex", (byte) 0);
                byte wiz = nutMap.getOrDefault("wiz", (byte) 0);

                while (pet.getLastAtrrib() >= 4) {
                    pet.setStr((short) (pet.getStr() + str));
                    pet.setWiz((short) (pet.getWiz() + wiz));
                    pet.setDex((short) (pet.getDex() + dex));
                    pet.setCon((short) (pet.getCon() + con));
                    pet.setLastAtrrib(getLastAttributePoint(pet));
                }
            }

            petAttribMonitor.end();
            petService.refreshPetInfo(role, pet);
        }

    }

    /**
     * 自动加相性
     */
    public void autoPolar(Role role) {
        byte status = role.getExtendBox().getAutoPolar().getOrDefault("status", (byte) 0);
        if (status == 1) {//开启自动
            byte first = role.getExtendBox().getAutoPolar().getOrDefault("one", (byte) 0);
            byte second = role.getExtendBox().getAutoPolar().getOrDefault("two", (byte) 0);
            byte third = role.getExtendBox().getAutoPolar().getOrDefault("there", (byte) 0);
            role.setLastPolar(getLastPolarPoint(role));
            while (role.getLastPolar() >= 1) {
                if (autoAddPolar(role, first)) continue;

                if (autoAddPolar(role, second)) continue;

                if (!autoAddPolar(role, third)) {
                    /**如果设置的前三个自动加点都加满了 这里应该跳出循环 否则死循环*/
                    break;
                }

            }
        }
    }

    private boolean autoAddPolar(Role role, int index) {
        boolean result = false;
        if (index == Const.SCHOOL_METAL && role.getMetal() < 30) {
            role.setMetal((short) (role.getMetal() + 1));
            result = true;
        } else if (index == Const.SCHOOL_WOOD && role.getWood() < 30) {
            role.setWood((short) (role.getWood() + 1));
            result = true;
        } else if (index == Const.SCHOOL_WATER && role.getWater() < 30) {
            role.setWater((short) (role.getWater() + 1));
            result = true;
        } else if (index == Const.SCHOOL_FIRE && role.getFire() < 30) {
            role.setFire((short) (role.getFire() + 1));
            result = true;
        } else if (index == Const.SCHOOL_EARTH && role.getEarth() < 30) {
            role.setEarth((short) (role.getEarth() + 1));
            result = true;
        }
        role.setLastPolar(getLastPolarPoint(role));
        return result;
    }

    /**
     * 宠物获得经验
     */
    public void addPetExp(Role role, int petId, int exp, boolean isPrint) {
        if (exp <= 0) {
            return;
        }

        Pet pet = SpringUtils.getPetService().getPetById(petId, role);
        if (pet != null) {
            if (pet.isLockexp()) {
                if (isPrint) {
//                    RespSyncMessage respSyncMessage = new RespSyncMessage();
//                    respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
//                    respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("由于你的#Y" + pet.getNickname() + "#n锁定了经验，无法获得经验。")));
                    MessagePusher.pushMessage(role, new RespNotifyMisc("由于你的#Y" + pet.getNickname() + "#n锁定了经验，无法获得经验。"));
                }
                return;
            }

            /**飞升前等级上限115，飞升后等级上限174*/
            int maxLevel = pet.isFly() ? 194 : 115;//宠物最高等级？
            if ((pet.getLevel()) < maxLevel) {
                if ((pet.getExp() + exp) >= getPetUpgradeNeedExp(pet.getLevel())) {
                    //这里应该是循环升级。
                    PetAttribMonitor petAttribMonitor = new PetAttribMonitor(role, pet);
                    // 可以升级
                    int level = pet.getLevel();
                    // 宠物最大 125级 并且最大等级不能超过人物15级
                    // 计算下一等级属性
                    int total = (int) ((pet.getExp() + exp) - getPetUpgradeNeedExp(level));
                    level++;
                    if (level >= maxLevel) {
                        level = maxLevel;
                    }
                    pet.setExp(total);
                    if (level == maxLevel) {
                        pet.setExp(0);
                    }
                    pet.setLevel((short) level);
                    pet.setLastResistPoint(getLastPolarPoint(pet));
                    pet.setLastAtrrib(getLastAttributePoint(pet));

                    pet.setBasicAttrib();//升级重新设置基础属性
                    pet.setCurrLife(countService.countPetLife(level, pet.getCon(), pet.getLifeEffect()));
                    pet.setCurrMana(countService.countPetMana(level, pet.getWiz(), pet.getManaEffect()));

                    // 升级置宠物技能
                    if (pet.getLevel() >= 20) {
                        setPetSkill(role, pet);
                    }
                    autoAddPoint(role, pet);

                    if (isPrint) {
//                        RespSyncMessage respSyncMessage = new RespSyncMessage();
//                        respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
                        String tips = "#R" + exp + "#n点经验";
                        addRewardTips(role, tips, true);
//                        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你的#Y" + pet.getName() + "#n获得了" + tips + "。")));
                        MessagePusher.pushMessage(role, new RespNotifyMisc("你的#Y" + pet.getName() + "#n获得了" + tips + "。"));

//                        respSyncMessage = new RespSyncMessage();
//                        respSyncMessage.setCode((short) 20481);
//                        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMiscEx("你的#Y" + pet.getName() + "#n升到#R" + level + "#n级了。")));
                        MessagePusher.pushMessage(role, new RespNotifyMiscEx("你的#Y" + pet.getName() + "#n升到#R" + level + "#n级了。"));
                        petService.loadPet(role, pet);


                        if (pet.isFly() == false && pet.getLevel() == maxLevel) {
                            String msg = MessageFormat.format("你的#Y{0}#n已经达到等级上限了，只有飞升后才能继续修炼。", pet.getName());
                            MessagePusher.pushMessage(role, new RespNotifyMiscEx(msg));
                        }
                    }


                    role.save();

                    petAttribMonitor.end();
                } else {
                    // 不能升级
                    int total = pet.getExp() + exp;
                    if (total > 2000000000) {
                        total = 2000000000;
                    } else if (total < 0) {
                        total = 0;
                    }
                    pet.setExp(total);
                    // 提示获得经验
                    if (isPrint) {
//                        RespSyncMessage respSyncMessage = new RespSyncMessage();
//                        respSyncMessage.setCode((short) Modules.MSG_NOTIFY_MISC);
                        String tips = "#R" + exp + "#n点经验";
                        addRewardTips(role, tips, true);
//                        respSyncMessage.setMsg(AsktaoUtil.getMessageBody(new RespNotifyMisc("你的#Y" + pet.getName() + "#n获得了" + tips + "。")));
                        MessagePusher.pushMessage(role, new RespNotifyMisc("你的#Y" + pet.getName() + "#n获得了" + tips + "。"));

                        List<FiedValue> list = new ArrayList<>();
                        list.add(new FiedValue(25, 3, pet.getExp()));
                        list.add(new FiedValue(55, 3, getPetUpgradeNeedExp(pet.getLevel())));
                        RespUpdate respUpdate = new RespUpdate();
                        respUpdate.setRoleId(pet.getId());
                        respUpdate.setList(list);
                        MessagePusher.pushMessage(role, respUpdate);
                    }
                    role.save();
                }
            }
            // 宠物超过等级，自动休息
            if (pet.getLevel() - role.getLevel() > 15) {
                if (pet.getId() == role.getPetBox().getFightPetId()) {
                    role.getPetBox().setFightPetId(0);
                }
                if (pet.getId() == role.getPetBox().getSupplyPetId()) {
                    role.getPetBox().setSupplyPetId(0);
                }
                RespSetCurrentPet respSetCurrentPet = new RespSetCurrentPet();
                respSetCurrentPet.setPetId(pet.getId());
                respSetCurrentPet.setStatus((short) 0);
                MessagePusher.pushMessage(role, respSetCurrentPet);
            }
        }
    }

    /**
     * 宠物升级置宠物技能
     */
    public void setPetSkill(Role role, Pet pet) {
        byte polar = pet.getPolar();
        ArrayList<Integer> skillList = new ArrayList<>();
        if (pet.getLevel() >= 20) {// 一阶技能
            if (polar == 1) {
                skillList.add(11);
            } else if (polar == 2) {
                skillList.add(61);
            } else if (polar == 3) {
                skillList.add(110);
            } else if (polar == 4) {
                skillList.add(161);
            } else if (polar == 5) {
                skillList.add(210);
            }
        }
        if (pet.getLevel() >= 40) {//二阶技能
            if (polar == 1) {
                skillList.add(12);
            } else if (polar == 2) {
                skillList.add(62);
            } else if (polar == 3) {
                skillList.add(111);
            } else if (polar == 4) {
                skillList.add(162);
            } else if (polar == 5) {
                skillList.add(211);
            }
        }
        if (pet.getLevel() >= 60) {//四阶技能
            if (polar == 1) {
                skillList.add(14);
            } else if (polar == 2) {
                skillList.add(64);
            } else if (polar == 3) {
                skillList.add(113);
            } else if (polar == 4) {
                skillList.add(164);
            } else if (polar == 5) {
                skillList.add(213);
            }
        }
        PetObject petObject = PetDataPool.name2PetObject.get(pet.getName());
        String targetNum = petObject.getTargetNum();
        String[] targetNumList ={};
        if(StringUtils.isNotEmpty(targetNum)){
            targetNumList = targetNum.split(",");
        }
        if (skillList.size() >= 1) {
            int i  = 0 ;
            for (Integer skillId : skillList) {
                RoleSkill petSkill = pet.getSkillBox().querySkillBy(skillId);

                Skill skill = skillService.getSkillInfo(skillId);
                if (petSkill == null) {
                    petSkill = new RoleSkill();
                    petSkill.setName(skill.getSkillName());
                    petSkill.setRoleId(pet.getId());
                    petSkill.setType((short) skill.getSkillType());
                    petSkill.setSkillId(skillId);
                    petSkill.setSkillJieshu(skill.getJeishu());
                    petSkill.setLevel((short) (pet.getLevel() * 1.6));
                    petSkill.setMana(skillService.getSkillMana(petSkill));
                    if(targetNumList.length>0){
                        petSkill.setTargetCount(Short.parseShort(targetNumList[i]));
                    }else{
                        petSkill.setTargetCount((short) skillService.getSkillTargetNum(petSkill));
                    }
                    pet.getSkillBox().learnSkill(petSkill);
                } else {
                    // 有技能存在 升级技能等级 等于宠物等级*1.6
                    petSkill.setLevel((short) (pet.getLevel() * 1.6));
                    petSkill.setMana(skillService.getSkillMana(petSkill));
                    if(targetNumList.length>0){
                        petSkill.setTargetCount(Short.parseShort(targetNumList[i]));
                    }else{
                        petSkill.setTargetCount((short) skillService.getSkillTargetNum(petSkill));
                    }

                }
                i +=1;
            }
            role.save();
        }
    }

    /**
     * 取人物升级所需经验
     *
     * @param level
     */

    public long getRoleUpgradeNeedExp(int level) {
        RoleExp roleExp = RoleDataPool.level2RoleExp.get((short) level);
        if (roleExp == null) {
            return 0;
        }
        return roleExp.getExp();
    }

    /**
     * 取元婴升级所需经验
     *
     * @param level
     */
    public long getRoleFlyUpNeedExp(int level) {
        RoleExp roleExp = RoleDataPool.level2RoleExp.get((short) level);
        if (roleExp == null) {
            return 0;
        }
        return roleExp.getUpgradeExp();
    }

    /**
     * 取宠物升级所需经验
     *
     * @param level
     * @return
     */
    public long getPetUpgradeNeedExp(int level) {
        PetExp petExp = RoleDataPool.level2PetExp.get((short) level);
        if (petExp == null) {
            return 0;
        }
        return petExp.getNextLevelExp();
    }

    /**
     * 经验丹增加的经验
     */
    public int getExpDanAddExp(int level) {
        return RoleDataPool.level2PetExp.get((short) level).getExpDan();
    }

    /**
     * 高级经验丹增加的经验
     */
    public int getHighExpDanAddExp(int level) {
        return RoleDataPool.level2PetExp.get((short) level).getHighExpDan();
    }

    /**
     * 根据相性取门派名称
     */
    public String getFamilyName(int polar) {
        String familyName = null;
        if (polar == 1) {
            familyName = "五龙山云霄洞";
        } else if (polar == 2) {
            familyName = "终南山玉柱洞";
        } else if (polar == 3) {
            familyName = "凤凰山斗阙宫";
        } else if (polar == 4) {
            familyName = "乾元山金光洞";
        } else if (polar == 5) {
            familyName = "骷髅山白骨洞";
        }
        return familyName;
    }

    private String replaceName(String name) {
        name = name.replace("#", "");
        name = name.replace("～", "");
        name = name.replace("~", "");
        name = name.replace("-", "");
        name = name.replace("_", "");
        name = name.replace("@", "");
        name = name.replace("G", "");
        name = name.replace("M", "");
        name = name.replace("g", "");
        name = name.replace("m", "");
        name = name.replace("Ｇ", "");
        name = name.replace("Ｍ", "");
        name = name.replace("ｇ", "");
        name = name.replace("ｍ", "");
        name = name.replace("全体", "");
        name = name.replace("运维", "");
        name = name.replace("。", "");
        name = name.replace("丶", "");
        name = name.replace("=", "");
        name = name.replace(":", "");
        name = name.replace("：", "");
        name = name.replace("\\", "");
//        name = name.replace("灬", "");//、
        name = name.replace("、", "");//＝
        name = name.replace("＝", "");//丶
        name = name.replace("丶", "");//￡
        name = name.replace("￡", "");//゛
        name = name.replace("゛", "");//゛
        name = name.replace(".", "");//゛
        name = name.replace("\uE814", "");//『
        name = name.replace("『", "");//『
        name = name.replace("』", "");//『
        name = name.replace("群", "");//『
        name = name.replace("裙", "");//『
        name = name.replace("裙", "");//『
        name = name.replace("Q", "");//『
        name = name.replace("q", "");//『
        name = name.replace("V", "");//『
        name = name.replace("X", "");//『
        name = name.replace("x", "");//『
        name = name.replace("w", "");//『
        name = name.replace("W", "");//『
        name = name.replace("信", "");//『
        name = name.replace("微", "");//『
        name = name.replace("利", "");//『
        name = name.replace("返", "");//『
        name = name.replace("术", "");//『
        name = name.replace("技", "");//『
        name = name.replace("v", "");//『
        //"群 裙 技 术 返 利 微 信 W X V Q q 客 服";

        Pattern p = Pattern.compile("[\\d]");
        Matcher matcher = p.matcher(name);
        String result = matcher.replaceAll("");
        return result.trim();
    }

    /**
     * 检测角色名是否合法
     */
    private boolean canCreateRole(IoSession session, String name) {
        Server server = serverService.getServer();
        if (Strings.isEmpty(name)) {
            MessagePusher.pushMessage(session, new RespMsg("请输入正确的角色名。（原因：9112）"));
            return false;
        }
        if (name.length() > 6) {
            MessagePusher.pushMessage(session, new RespMsg("角色名称过长。（原因：9111）"));
            return false;
        }
        name = replaceName(name);
        if (name.length() <= 1) {
            MessagePusher.pushMessage(session, new RespMsg("请输入正确的角色名。（原因：9111）"));
            return false;
        }
        //敏感词检测
        List<String> set = wordService.checkDirtyWords(name);
        if (set.size() >= 1) {
            MessagePusher.pushMessage(session, new RespMsg("角色名存在非法字符。（原因：9113）"));
            return false;
        }

        if (SpringUtils.getBean(ChatService.class).checkQQNumber(name)) {
            MessagePusher.pushMessage(session, new RespMsg("角色名存在非法字符。（原因：9114）"));
            return false;
        }
        Pattern CHECK_EMOJI = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
        Matcher emojiTitle = CHECK_EMOJI.matcher(name);
        if (emojiTitle.find()) {
            MessagePusher.pushMessage(session, new RespMsg("角色名存在非法字符。（原因：9113）"));
            return false;
        }
//        int nameCount = dao.count(Role.class, Cnd.where("name", "=", name).and("distName", "=", server.getName()));
//        if (nameCount >= 1) {
//            MessagePusher.pushMessage(session, new RespMsg("这个角色名字已经存在。（原因：9113）"));
//            return false;
//        }
        if (!SpringUtils.getPlayerService().occupyName(name, 0L)) {
            MessagePusher.pushMessage(session, new RespMsg("这个角色名字已经存在。（原因：9113）"));
            return false;
        }
        return true;
    }

    public Role createRole(IoSession session, String sid, ReqCreateNewChar reqCreateNewChar) {
        Server server = serverService.getServer();
        // 每个区的角色名称不能重复
        String name = reqCreateNewChar.getChar_name().trim();
        name = name.replace("#", "");
        if (!canCreateRole(session, name)) {
            return null;
        }
        name = replaceName(name);
        Role role = new Role();
        role.setSid(sid.substring(sid.length() - 8));
        role.setRoleId(getRoleId());
        role.setName(name);
        role.setPolar(reqCreateNewChar.getPolar());
        role.setGender((byte) reqCreateNewChar.getGender());
        role.setCreateTime(new Date());
        role.setSaveLoyalty(300);
        role.setSaveLife(0);
        role.setSaveMana(0);
        role.setLevel((short) 1);
        role.setLastAttrib((short) (0));
        //role.setSiver(10000000);

        role.setPos(new Pos());
        role.setPropsStatus(NutMap.NEW());
        role.setGold2money(NutMap.NEW());

        role.setExtendBox(new PlayerExtendBox());

        Map<String, Byte> autoAttrib = role.getExtendBox().getAutoAttrib();
        autoAttrib.put("con", (byte) 0);
        autoAttrib.put("str", (byte) 3);
        autoAttrib.put("dex", (byte) 1);
        autoAttrib.put("wiz", (byte) 0);
        autoAttrib.put("status", (byte) 1);
        autoAttrib.put("type", (byte) 1);
//        role.setAutoAttrib(NutMap.NEW().setv("con", 0).setv("str", 3).setv("dex", 1).setv("wiz", 0)
//                .setv("status", 1).setv("type", 1));


        Map<String, Byte> autoPolar = role.getExtendBox().getAutoPolar();
        autoPolar.put("one", (byte) 5);
        autoPolar.put("two", (byte) 4);
        autoPolar.put("there", (byte) 2);
        autoPolar.put("status", (byte) 1);
        autoPolar.put("type", (byte) 1);
//        role.setAutoPolar(
//                NutMap.NEW().setv("one", 5).setv("two", 4).setv("there", 2).setv("status", 1).setv("type", 1));

        ArrayList<FriendGroup> arrayList = new ArrayList<>();
        FriendGroup friendGroup = new FriendGroup();
        friendGroup.setNumber("1");
        friendGroup.setGroupName("我的好友");
        arrayList.add(friendGroup);
        role.getFriendBox().setFriendGroup(arrayList);

        LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
        TitleInfo titleInfo = new TitleInfo();
        titleInfo.setType("无显示");
        hashMap.put(titleInfo.getType(), titleInfo);

        role.setRoleIcon(mapService.heroIcon(role.getGender(), role.getPolar()));
        role.setDistName(server.getName());
        role.setUid(IdGenerator.getNextId());

        role.doAfterInit();
        SpringUtils.getPlayerService().saveToCache(role);

        role.setCurrLife(role.getMaxLife());
        role.setCurrMana(role.getMaxMana());
        /**创建时算第1天*/
        role.setLoginDays(1);
        role.save();

        SpringUtils.getPlayerService().addPlayerProfile(new PlayerProfile(role));

        return role;
    }

    /**
     * 处理创建角色事件
     */
    @EventHandler(EventType.CREATE_ROLE)
    public void handleCreateRoleEvent(CreateRoleEvent createRoleEvent) {
        Role role = createRoleEvent.getRole();
        RoleService roleService = SpringUtils.getRoleService();
        /**创建角色的时候把新手装备3件套穿到身上*/
        giftPetAndEquip(role);
        role.setCurrLife(role.getMaxLife());
        role.setCurrMana(role.getMaxMana());
        /**创建角色时获得随心时装礼盒*/
//        equipService.addMall("随心时装礼盒", false, role, 1);
//        List<String> list = new ArrayList<>(ItemDataPool.name2ChangeCard.keySet());
//        int index = ThreadLocalRandom.current().nextInt(list.size());
        SpringUtils.getBean(ChangeCardService.class).getChangeCard(role, "超级朱雀卡");
        SpringUtils.getBean(ChangeCardService.class).getChangeCard(role, "超级疆良卡");
        SpringUtils.getBean(ChangeCardService.class).getChangeCard(role, "超级东山神灵卡");

        Account account = accountService.getAccount(role.getSid());
        if (account == null) {
            return;
        }

        String new_person_title = DataCache.REDIS_DATA.get("new_person_title");
        int new_person_jifen =  Integer.parseInt(DataCache.REDIS_DATA.get("new_person_jifen"));
        int new_person_jinqian =  Integer.parseInt(DataCache.REDIS_DATA.get("new_person_jinqian"));
        int new_person_yinyuanbao =  Integer.parseInt(DataCache.REDIS_DATA.get("new_person_yinyuanbao"));
        int new_person_jinyuanbao =  Integer.parseInt(DataCache.REDIS_DATA.get("new_person_jinyuanbao"));
        String new_person_zuoqi = DataCache.REDIS_DATA.get("new_person_zuoqi");
        String new_person_chongwu = DataCache.REDIS_DATA.get("new_person_chongwu");
        int new_person_qianneng =  Integer.parseInt(DataCache.REDIS_DATA.get("new_person_qianneng"));
        int new_person_daijinquan =  Integer.parseInt(DataCache.REDIS_DATA.get("new_person_daijinquan"));

        if(account.getIsuse() != 1){
            roleService.addGold(role, new_person_jinyuanbao, Reason.GM_ADD_MONEY);
            account.setIsuse(1);
            dao.insertOrUpdate(account);
        }
        roleService.addSiver(role, new_person_yinyuanbao, Reason.GM_ADD_MONEY);
        roleService.addMoney(role, new_person_jinqian, hdds_buy);
        payService.jifen(role, new_person_jifen);
        payService.choujiang(role, 0);
        roleService.addPot(role, new_person_qianneng);
        roleService.addVoucher(role, new_person_daijinquan);

        String new_person_item = DataCache.REDIS_DATA.get("new_person_item");
        for (String s : new_person_item.split("\\+")) {
            SpringUtils.getBean(NewDropService.class).addRewardTask(role,s,"");
        }

        //新人奖励
        SpringUtils.getRoleService().addTitle(role, new TitleInfo(new_person_title, new_person_title));
        //SpringUtils.getRoleService().addTitle(role, new TitleInfo("虎福生财", "虎福生财"));
//        {
//            Mail mail = SpringUtils.getMailService().createMail("新建角色活动", "新建角色活动", 1 * TimeUtil.ONE_DAY);
//            String[] strings = {"混元金斗", "番天印", "阴阳镜", "定海珠", "金蛟剪", "九龙神火罩", "卸甲金葫"};
//            int index = new Random().nextInt(strings.length);
//            ArrayList<NutMap> maps = new ArrayList<>();
//            maps.add(new NutMap().setv("data", "#I物品|" + strings[index] + "#r1#I").setv("type", Const.rewardFabao).setv("petName", strings[index]).setv("level", 1));
//            //maps.add(new NutMap().setv("data", "#I宠物|"+names[index]+"(精怪)#r1#I").setv("type", Const.mailPet).setv("petName", names[index]).setv("value",1));
//            mail.getDatas().addAll(maps);
//            SpringUtils.getMailService().sendNewMail(role,mail);
//        }
        {
            Mail mail = SpringUtils.getMailService().createMail("新建角色活动", "新建角色活动", 1 * TimeUtil.ONE_DAY);
            ArrayList<NutMap> maps = new ArrayList<>();
            maps.add(new NutMap().setv("data", "#I宠物|"+new_person_zuoqi+"(精怪)#r1#I").setv("type", Const.rewardChongwu).setv("petName",new_person_zuoqi).setv("value",1));
            mail.getDatas().addAll(maps);
            SpringUtils.getMailService().sendNewMail(role,mail);
        }
        {

            Mail mail = SpringUtils.getMailService().createMail("新建角色活动", "新建角色活动", 1 * TimeUtil.ONE_DAY);
            ArrayList<NutMap> maps = new ArrayList<>();
            maps.add(new NutMap().setv("data", "#I宠物|"+new_person_chongwu.split("-")[1]+"("+new_person_chongwu.split("-")[0]+")#r1#I").setv("type", Const.rewardChongwu).setv("petName", new_person_chongwu.split("-")[1]).setv("value",1));
            mail.getDatas().addAll(maps);
            SpringUtils.getMailService().sendNewMail(role,mail);
        }

        //发送消息
        SchedulerManager.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                MessagePusher.pushMessage(role, new RespMsg("#Y新手赠送的#n#R【坐骑和宠物】#n#Y请到#n#R邮箱#n#Y领取，其他赠送已经直接发放到#n#R背包"));
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("#Y新手赠送的#n#R【坐骑和宠物】#n#Y请到#n#R邮箱#n#Y领取，其他赠送已经直接发放到#n#R背包"));
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("#Y新手赠送的#n#R【坐骑和宠物】#n#Y请到#n#R邮箱#n#Y领取，其他赠送已经直接发放到#n#R背包"));
            }
        }, 5000);


    }



    /**
     * 移动
     *
     * @param role
     * @param reqMultiMoveTo
     */
    public void recordPosition(Role role, ReqMultiMoveTo reqMultiMoveTo) {
        List<Position> list = reqMultiMoveTo.getList();
        Position position = list.get(list.size() - 1);// 最后一个位置
        //System.out.println("移动地图："+reqMultiMoveTo.getMapId()+"X:"+position.getX()+"Y:"+position.getY());
        Pos pos = role.getPos();
        pos.setX(position.getX());
        pos.setY(position.getY());
        pos.setDir((byte)reqMultiMoveTo.getDir());
        role.setPos(pos);
//        ConcurrentHashSet<Integer> set = SpringUtils.getMapService().getRoleIds(new GroupMapParam(role), reqMultiMoveTo.getMapId());
//        broadcastService.broadcastMove(role, set);

        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, 40);
        if(roleEquip == null){

        }else {
            int type = FlyTypeEnums.getType(roleEquip.getName());
            if(type>=3){
                // 组队判断
                Team team = SpringUtils.getTeamService().getTeam(role.getRoleId());
                if (team != null && SpringUtils.getTeamService().isInTeam(role)) {
                    for( Member member : team.getList()){
                        if (member == null) {
                            continue;
                        }
                        /**暂离的不用判断*/
                        if (member.isInTeam() == false) {
                            continue;
                        }

                        Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                        if (memberRole == null) {
                            continue;
                        }
                        Pos memberPos = memberRole.getPos();
                        memberPos.setX(position.getX());
                        memberPos.setY(position.getY());
                        memberPos.setDir((byte)reqMultiMoveTo.getDir());
                        memberRole.setPos(memberPos);
                        //  SceneManager.INSTANCE.movePosition(memberRole);
                    }
                }
            }
        }

    }

    public void openAutoFight(Role role, Fight fight) {
        try {
            FightObject fightObject = fight.queryFightObject(role.getRoleId());
            if (fightObject == null) {
                return;
            }
            /**开启自动战斗*/
            if (role.getAutoFight() == 1) {
                fightObject.setAutoFight((byte) 1);
                ScheduledFuture<?> timer = fight.getTimeOutTask();
                if (timer != null && (!timer.isDone() || !timer.isCancelled()) && !fightObject.isDoAction()) {
                    RespAutoFightSkill respAutoFightSkill = new RespAutoFightSkill();
                    SkillAutoPicker autoPicker = fightService.getAutoObject(fightObject, fight);
                    ReqFightDoAction doAction = new ReqFightDoAction();
                    doAction.setAttackerId(fightObject.getId());
                    doAction.setTargetId(autoPicker.getTargetId());
                    doAction.setSkillId(autoPicker.getSkillId());
                    if (autoPicker.isDef()) {
                        doAction.setType(FightAction.DEFENSE);
                    } else {
                        if (doAction.getSkillId() == FightAction.PHYSICAL_ATTACK) {
                            doAction.setType(FightAction.PHYSICAL_ATTACK);// 物攻
                        } else if (SpringUtils.getArtifactService().isArtifactSkill(doAction.getSkillId())) {
                            doAction.setType(FightAction.ARTIFACT_EXTRA_SKILL);
                        } else {
                            doAction.setType(FightAction.CAST_MAGIC);
                        }
                    }
                    respAutoFightSkill.setUser_action((byte) doAction.getType());
                    respAutoFightSkill.setRoleSkillId(doAction.getSkillId());
                    if (fightObject.getMultiIndex() == 1) {
                        respAutoFightSkill.setRoleIsGroup(true);
                        respAutoFightSkill.setRoleRound((byte) autoPicker.getLastRound());
                        respAutoFightSkill.setUser_next_action((byte) autoPicker.getNextType());
                        respAutoFightSkill.setRoleNextSkillId(autoPicker.getNextSkillId());
                    }
                    SpringUtils.getFightService().doAction(doAction);

                    if (fightObject.getFightPetId() > 0) {
                        FightObject petObject = fight.queryFightObject(fightObject.getFightPetId());
                        if (petObject != null && !petObject.isFallDown()) {
                            autoPicker = fightService.getAutoObject(petObject, fight);
                            doAction = new ReqFightDoAction();
                            doAction.setAttackerId(petObject.getId());
                            doAction.setTargetId(autoPicker.getTargetId());
                            doAction.setSkillId(autoPicker.getSkillId());
                            if (autoPicker.isDef()) {
                                doAction.setType(FightAction.DEFENSE);
                            } else {
                                if (doAction.getSkillId() == FightAction.PHYSICAL_ATTACK) {
                                    doAction.setType(FightAction.PHYSICAL_ATTACK);// 物攻
                                } else if (SpringUtils.getArtifactService().isArtifactSkill(doAction.getSkillId())) {
                                    doAction.setType(FightAction.ARTIFACT_EXTRA_SKILL);
                                } else {
                                    doAction.setType(FightAction.CAST_MAGIC);
                                }
                            }
                            SpringUtils.getFightService().doAction(doAction);
                            respAutoFightSkill.setPet_action((byte) doAction.getType());
                            respAutoFightSkill.setPetSkillId(doAction.getSkillId());
                            if (petObject.getMultiIndex() == 1) {
                                respAutoFightSkill.setPetIsGroup(true);
                                respAutoFightSkill.setPetRound((byte) autoPicker.getLastRound());
                                respAutoFightSkill.setPet_next_action((byte) autoPicker.getNextType());
                                respAutoFightSkill.setPetNextSkillId(autoPicker.getNextSkillId());
                            }
                        }
                    }
                    MessagePusher.pushMessage(role, respAutoFightSkill);
                }
            } else {
                /**关闭自动战斗*/
                fightObject.setAutoFight((byte) 0);
                /**释放定时器**/
                fight.removeHostTask(fightObject.getId());
                fight.removePetTask(fightObject.getFightPetId());
            }
        } catch (Exception e) {
            log.error("战斗中设置自动战斗错误=让目标防御={}", Lang.getStackTrace(e));
            ReqFightDoAction ReqFightDoAction = new ReqFightDoAction();
            ReqFightDoAction.setAttackerId(role.getRoleId());
            ReqFightDoAction.setTargetId(role.getRoleId());
            ReqFightDoAction.setSkillId(0);
            ReqFightDoAction.setType(1);
            SpringUtils.getFightService().doAction(ReqFightDoAction);
        }
    }

    /**
     * 变更称谓
     */
    public void changeTitle(Role role, String type) {
        LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
        if (hashMap == null) {
            return;
        }
        String title = hashMap.get(type).getTitle();
        if (!Strings.isEmpty(title) || type.equals("无显示")) {// 存在称谓
            RespUpdate respUpdate = new RespUpdate();
            respUpdate.setRoleId(role.getRoleId());
            ArrayList<FiedValue> list = new ArrayList<>();
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType((short) 36);
            fiedValue.setValue(title);
            fiedValue.setVT((byte) 4);
            list.add(fiedValue);
            respUpdate.setList(list);
            MessagePusher.pushMessage(role, respUpdate);
            role.setCurrTitle(title);
            role.save();
            /**发送增益**/
            sendExtraAttribute(role);
            broadcastService.sendUpdateAppear(role);
        }
    }

    /**
     * 添加称谓
     */
    public void addTitle(Role role, TitleInfo titleInfo) {
        ArrayList<TitleInfo> list = new ArrayList<>();
        LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
        LinkedHashMap<String, TitleInfoDate> hashMapDate = role.getExtendBox().getTitleDateList();
        if (hashMap == null) {
            hashMap = new LinkedHashMap<>();
            TitleInfo title = new TitleInfo();
            title.setType("无显示");
            hashMap.put(title.getType(), title);
        }
        if(hashMapDate ==null){
            hashMapDate = new LinkedHashMap<>();
        }
        boolean sendMsg = true;
        for (Map.Entry<String, TitleInfo> entry : hashMap.entrySet()) {
            if (titleInfo.getTitle().equals(entry.getValue().getTitle())) {
                sendMsg = false;
            }
        }
        if (sendMsg) {
            RespNotifyMisc respMsg = new RespNotifyMisc();
            respMsg.setMsg("恭喜你，获得了#R" + titleInfo.getTitle() + "#n称谓。");
            respMsg.setTime(new Long(new Date().getTime() / 1000).intValue());
            MessagePusher.pushMessage(role, respMsg);
        }
        hashMap.put(titleInfo.getType(), titleInfo);
        TitleInfoDate t= new TitleInfoDate();
        t.setTitle(titleInfo.getType());
        t.setTime(new Date());
        hashMapDate.put(titleInfo.getType(),t);
        for (Map.Entry<String, TitleInfo> entry : hashMap.entrySet()) {
            list.add(entry.getValue());
        }
        RespTitleList respTitleList = new RespTitleList();
        respTitleList.setList(list);
        MessagePusher.pushMessage(role, respTitleList);
        changeTitle(role, titleInfo.getType());
        titleTask(role);//初始化称号任务
        role.save();
    }

    /**
     * 发送人物增益
     */
    public void sendExtraAttribute(Role role) {
        refreshRoleBasic(role);
        AttrService attrService = SpringUtils.getBean(AttrService.class);
        RespUpdateImprovement respUpdateImprovement = new RespUpdateImprovement();
        respUpdateImprovement.setId(role.getRoleId());
        LinkedHashMap<Short, FiedValue> extraAttribute = attrService.countExtraAttribute(role);
        ArrayList<FiedValue> fieldValues = new ArrayList<>();
        for (Map.Entry<Short, FiedValue> entry : extraAttribute.entrySet()) {
            FiedValue fiedValue = entry.getValue();
            fiedValue.setValue(attrService.getValue(fiedValue.getValue()));
            fieldValues.add(fiedValue);
        }
        respUpdateImprovement.setList(fieldValues);
        MessagePusher.pushMessage(role, respUpdateImprovement);

        List<RoleSkill> roleSkillList = role.getSkillBox().queryAllSkills();
        RespUpdateSkill respUpdateSkill = new RespUpdateSkill();
        respUpdateSkill.setId(role.getRoleId());
        ArrayList<SkillInfo> skillInfos = new ArrayList<>();
        for (RoleSkill roleSkill : roleSkillList) {
            skillInfos.add(skillService.getSkillInfo(roleSkill, role.getExtraSkillLevel()));
            Skill skill = SkillDataPool.id2Skill.get(roleSkill.getSkillId());
            if (skill != null) {
                roleSkill.setName(skill.getSkillName());
            }
            role.getSkillBox().getSkills().put(roleSkill.getSkillId(), roleSkill);
        }

        respUpdateSkill.setList(skillInfos);
        MessagePusher.pushMessage(role, respUpdateSkill);

        broadcastService.updateAppearance(role);
////应该能全部达到
        //broadcastService.update_zhanli(role);


    }

    /**
     * 角色改名
     *
     * @param role
     * @param newName
     */
    public void modifyName(Role role, String newName) {
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        if (serverService.getServer().getId() == 10000) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("跨服试道中不能改名。"));
            return;
        }
        int count = equipService.getCount("改头换面卡", true, role);
        if (count <= 0) {
            return;
        }
        if (Strings.isEmpty(newName)) {
            MessagePusher.pushMessage(role, new RespMsg("角色名不能为空。"));
            return;
        }

        newName = replaceName(newName);
        if (newName.length() <= 1) {
            MessagePusher.pushMessage(role, new RespMsg("输入的内容存在敏感词。"));
            return;
        }
        if (newName.contains("�")) {
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("昵称只允许数字、中文、字母。。"));
            return;
        }
        Pattern p = Pattern.compile(RoleController.filterStr);
        Matcher m = p.matcher(newName);
        if (m.find()) {
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("昵称只允许数字、中文、字母。"));
            return;
        }
        List<String> set = wordService.checkDirtyWords(newName);
        if (set.size() >= 1) { //敏感词检测
            MessagePusher.pushMessage(role, new RespMsg("输入的内容存在敏感词。"));
            return;
        }
        if (SpringUtils.getBean(ChatService.class).checkQQNumber(newName)) {
            MessagePusher.pushMessage(role, new RespMsg("角色名存在非法字符。（原因：9114）"));
            return;
        }
//        int nameCount = dao.count(Role.class, Cnd.where("name", "=", newName).and("distName", "=", role.getDistName()));
        if (!SpringUtils.getPlayerService().occupyName(newName, role.getUid())) {
            MessagePusher.pushMessage(role, new RespMsg("这个角色名字已经存在。（原因：9113）"));
            return;
        }
        equipService.delRoloEquip("改头换面卡", 1, true, role);
        String oldName = role.getName();
        Set<String> nameList = role.getExtendBox().getNameList();
        nameList.add(oldName);
        role.setName(newName);
        role.save();
        // 让玩家重上
        SpringUtils.getPlayerService().updateRoleName(oldName, role);

//        RespOperRename respOperRename = new RespOperRename();//Todo 好像没有必要发 发了关闭不了这个界面
//        respOperRename.setMsg("角色名修改成功，将即将重新登录。");
//        respOperRename.setNewName(role.getName());
//        MessagePusher.pushMessage(session, respOperRename);

        RespChat respChat = new RespChat();
        respChat.setMsg("#Y" + oldName + "#n成功更名为#Y" + newName + "#n。");
        respChat.setType(ChatConst.SYSTEM);
        respChat.setRoleName(role.getName());
        respChat.setLineName(serverService.getServer().getSonName());
        respChat.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
        SenderUtils.pushChatMessage(respChat);
        // 通知好友重新加载好友名字
        serverService.getScheduledExecutorService().schedule(new Runnable() {
            @Override
            public void run() {
                for (Friend friend : role.getFriendBox().getFriends()) {
                    Role friendRole = SpringUtils.getRoleService().getOnlinePlayer(Long.parseLong(friend.getGid()));
                    if (friendRole == null) {
                        continue;
                    }
                    SpringUtils.getFriendService().loadFriends(friendRole);
                }
            }
        }, 3, TimeUnit.SECONDS);

        /**产生一个角色改名事件*/
        EventDispatcher.getInstance().fireEvent(new RoleNameChangeEvent(EventType.ROLE_NAME_CHANGE, role, oldName, newName));

        switchServer(role);
    }

    /**
     * 切换线路 重上
     */
    private void switchServer(Role role) {
        LoginAuth request = new LoginAuth();
        DataCache.LOGIN_AUTHS.put(role.getSid(), request);
        IoSession session = SessionUtils.getSessionBy(role.getUid());
        if (session != null) {
            session.closeNow();
        }
//        MessagePusher.pushMessage(role,new RespChatUseCard());
//        RespSwitchServer respSwitchServer = new RespSwitchServer();
//        respSwitchServer.setResult((short) 1);
//        respSwitchServer.setContent(serverService.getServer().getSonIp() + "," + serverService.getServer().getSonPort()
//                + "," + request.getAuthKey() + "," + request.getSeed() + "," + role.getName());
//        MessagePusher.pushMessage(role, respSwitchServer);
    }

    /**
     * 角色修改性别
     *
     * @param role
     */
    public void modifySex(Role role) {
        int count = equipService.getCount("改头换面卡", true, role);
        if (count <= 0) {
            return;
        }
        RoleEquip head = equipService.getRoleEquipByPos(role, 2);
        if (head != null) {// 如果有帽子 修改性别ICON
            equipService.changeEquipSex(head);
        }
        RoleEquip clothes = equipService.getRoleEquipByPos(role, 3);
        if (clothes != null) {// 如果有衣服 修改性别ICON
            equipService.changeEquipSex(clothes);
        }

        equipService.delRoloEquip("改头换面卡", 1, true, role);
        role.setGender((byte) (role.getGender() == 1 ? 2 : 1));
        role.setRoleIcon(mapService.heroIcon(role.getGender(), role.getPolar()));
        // 卸下身上时装 置Icon为0
        fasionService.unEquipCustomFasion(role, (short) 31, false);
        fasionService.unEquipCustomFasion(role, (short) 33, false);
        fasionService.unEquipCustomFasion(role, (short) 34, false);
        fasionService.unEquipCustomFasion(role, (short) 35, false);
        fasionService.unEquipCustomFasion(role, (short) 36, false);
        role.setMount(0);
        role.setMountIcon(0);
        role.setMoveSpeed(0);
        role.setMountPosture(0);
        role.setCustomFasion("");
        role.setCustom(false);
        role.save();

        SpringUtils.getPlayerService().updateRoleIcon(role);// 更新Icon
        RespChat respChat = new RespChat();
        respChat.setMsg(String.format("#Y%s#n使用了#R改头换面卡#n，成功将性别转换为#R%s性#n。", role.getName(), (role.getGender() == 1 ? "男" : "女")));
        respChat.setType(ChatConst.SYSTEM);
        respChat.setRoleName(role.getName());
        respChat.setLineName(serverService.getServer().getSonName());
        respChat.setTime(new Long(System.currentTimeMillis() / 1000).intValue());
        SenderUtils.pushChatMessage(respChat);

        MessagePusher.pushMessage(role, new RespChangeSex(role.getGender()));
        // 让玩家重上

        switchServer(role);
    }

    public void sendAutoSet(Role role) {
        try {
            NutMap publicAutoSet = NutMap.NEW();
            publicAutoSet.setv("type", 2);
            publicAutoSet.setv("action", 1);
            publicAutoSet.setv("skillId", 2);
            publicAutoSet.setv("multi", 0);
            publicAutoSet.setv("list", new ArrayList<>());

            if (role == null)
                return;
            {
                Map<String, Object> autoSet = role.getExtendBox().getAutoFightSet();
                if (autoSet == null || autoSet.size() == 0) {
                    autoSet = publicAutoSet;
                }
                RespFightCommandInfo respFightCommandInfo = new RespFightCommandInfo();
                respFightCommandInfo.setId(role.getRoleId());
                respFightCommandInfo.setType(((Integer) autoSet.get("type")).shortValue());
                respFightCommandInfo.setSkillId(((Integer) autoSet.get("skillId")).shortValue());
                respFightCommandInfo.setAuto_select(((Integer) autoSet.get("action")).byteValue());
                respFightCommandInfo.setMulti_index(((Integer) autoSet.get("multi")).byteValue());
                respFightCommandInfo.setList((List<SkillGroup>) autoSet.get("list"));
                MessagePusher.pushMessage(role, respFightCommandInfo);
            }
            if (role.getPetBox().getFightPetId() >= 1) {
                Pet pet = petService.getPetById(role.getPetBox().getFightPetId(), role);
                if (pet != null) {
                    Map<String, Object> autoSet = pet.getAutoFightSet();
                    if (autoSet == null || autoSet.size() == 0) {
                        autoSet = publicAutoSet;
                    }
                    RespFightCommandInfo respFightCommandInfo = new RespFightCommandInfo();
                    respFightCommandInfo.setId(pet.getId());
                    respFightCommandInfo.setType(((Integer) autoSet.get("type")).shortValue());
                    respFightCommandInfo.setSkillId((Integer) autoSet.get("skillId"));
                    respFightCommandInfo.setMulti_index(((Integer) autoSet.get("multi")).byteValue());
                    respFightCommandInfo.setAuto_select(((Integer) autoSet.get("action")).byteValue());
                    respFightCommandInfo.setList((List<SkillGroup>) autoSet.get("list"));
                    MessagePusher.pushMessage(role, respFightCommandInfo);
                }
            }
        } catch (Exception e) {
            log.error("发送自动技能状态出错=={}", Lang.getStackTrace(e));
        }

    }

    public void delTitle(Role role, String titleType) {
        TitleInfo delTitleInfo = null;
        LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
        for (Map.Entry<String, TitleInfo> entry : hashMap.entrySet()) {
            if (entry.getKey().equals(titleType)) {
                delTitleInfo = hashMap.remove(entry.getKey());
                if (role.getCurrTitle() != null && role.getCurrTitle().equals(entry.getValue().getTitle())) {
                    RespUpdate respUpdate = new RespUpdate();
                    respUpdate.setRoleId(role.getRoleId());
                    ArrayList<FiedValue> list = new ArrayList<>();
                    list.add(new FiedValue(36, 4, ""));
                    respUpdate.setList(list);
                    MessagePusher.pushMessage(role, respUpdate);
                    role.setCurrTitle("");
                    role.save();
                    if (isOnline(role)) {
                        //删除称号更新外观
                        broadcastService.sendUpdateAppear(role);
                        //删除称号更新属性
                        sendExtraAttribute(role);
                        //刷新任务
                        titleTask(role);//初始化称号任务
                    }
                }
                break;
            }
        }

        /**删除对应称号时，更新客户端数据*/
        if (delTitleInfo != null) {
            RespTitleList respTitleList = getRespTitleList(hashMap);
            MessagePusher.pushMessage(role, respTitleList);

            String content = I18nIdDataPool.getI18nContent(I18nId.PMT_501, delTitleInfo.getTitle());
            MessagePusher.pushMessage(role, new RespNotifyMisc(content));
        }
    }

    /**
     * 获得更新称号返回
     */
    private RespTitleList getRespTitleList(LinkedHashMap<String, TitleInfo> hashMap) {
        List<TitleInfo> list = new ArrayList<>();
        for (Map.Entry<String, TitleInfo> entry : hashMap.entrySet()) {
            list.add(entry.getValue());
        }
        RespTitleList respTitleList = new RespTitleList();
        respTitleList.setList(list);
        return respTitleList;
    }

    /**
     * 更新称号
     */
    public void changeTitle(Role role, TitleInfo titleInfo) {
        TitleInfo existsTitleInfo = null;
        LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
        for (Map.Entry<String, TitleInfo> entry : hashMap.entrySet()) {
            if (entry.getKey().equals(titleInfo.getType())) {
                existsTitleInfo = hashMap.get(entry.getKey());
                String oldTitle = existsTitleInfo.getTitle();
                existsTitleInfo.setTitle(titleInfo.getTitle());
                role.save();

                if (role.getCurrTitle().equals(oldTitle)) {
                    RespUpdate respUpdate = new RespUpdate();
                    respUpdate.setRoleId(role.getRoleId());
                    ArrayList<FiedValue> list = new ArrayList<>();
                    list.add(new FiedValue(36, 4, titleInfo.getTitle()));
                    respUpdate.setList(list);
                    MessagePusher.pushMessage(role, respUpdate);
                    role.setCurrTitle(titleInfo.getTitle());
                    role.save();
                    if (isOnline(role)) {
                        broadcastService.sendUpdateAppear(role);
                    }
                }

                String content = I18nIdDataPool.getI18nContent(I18nId.PMT_502, oldTitle, titleInfo.getTitle());
                MessagePusher.pushMessage(role, new RespNotifyMisc(content));

                break;
            }
        }


        if (existsTitleInfo != null) {
            RespTitleList respTitleList = getRespTitleList(hashMap);
            MessagePusher.pushMessage(role, respTitleList);
        }
    }

    /**
     * 查看玩家信息
     */
    public void checkRoleInfo(IoSession session, ReqCheckPlayer reqCheckPlayer) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        //查看玩家信息
        if (Strings.isEmpty(reqCheckPlayer.getChar_gid())) {
            return;
        }
        String gid = reqCheckPlayer.getChar_gid();
        long uid = Long.parseLong(gid);
        if (SpringUtils.getPlayerService().queryPlayerProfile(uid) == null) return;
        String lineName = serverService.getServer().getSonName();
        Role toRole = SpringUtils.getRoleService().getOnlinePlayer(uid);
        if (toRole != null) {
            if (Const.ROLEINFO_EX_DLG_TYPE.contains(reqCheckPlayer.getDlg_type())) {
                RespRoleInfoEx respRoleInfo = new RespRoleInfoEx();
                respRoleInfo.setPolar((byte) role.getPolar());
                respRoleInfo.setMsg_type(reqCheckPlayer.getDlg_type());
                respRoleInfo.setAccount(role.getSid());
                respRoleInfo.setParty(toRole.getPartyName());
                respRoleInfo.setIcon(toRole.getRoleIcon());
                respRoleInfo.setLevel(toRole.getLevel());
                respRoleInfo.setGid(toRole.getGid());
                respRoleInfo.setRoleId(toRole.getRoleId());
                respRoleInfo.setName(toRole.getName());
                if (SpringUtils.getTeamService().isTeamLeader(toRole)) {
                    respRoleInfo.setStatus(Const.TITLE_TEAM_LEADER);
                } else if (SpringUtils.getTeamService().isInTeam(toRole)) {
                    respRoleInfo.setStatus(Const.TITLE_IN_TEAM);
                }
                respRoleInfo.setServerId(lineName.substring(lineName.length() - 2));
                MessagePusher.pushMessage(session, respRoleInfo);
            } else {
                RespRoleInfo respRoleInfo = new RespRoleInfo();
                respRoleInfo.setPolar((byte) role.getPolar());
                respRoleInfo.setMsg_type(reqCheckPlayer.getDlg_type());
                respRoleInfo.setAccount(role.getSid());
                respRoleInfo.setParty(toRole.getPartyName());
                respRoleInfo.setIcon(toRole.getRoleIcon());
                respRoleInfo.setLevel(toRole.getLevel());
                respRoleInfo.setGid(toRole.getGid());
                respRoleInfo.setRoleId(toRole.getRoleId());
                respRoleInfo.setName(toRole.getName());
                if (SpringUtils.getTeamService().isTeamLeader(toRole)) {
                    respRoleInfo.setStatus(Const.TITLE_TEAM_LEADER);
                } else if (SpringUtils.getTeamService().isInTeam(toRole)) {
                    respRoleInfo.setStatus(Const.TITLE_IN_TEAM);
                }
                if (SpringUtils.getFightService().isInFight(toRole)) {
                    respRoleInfo.setStatus(Const.TITLE_LOOKON);
                }
                respRoleInfo.setServerId(lineName.substring(lineName.length() - 2));
                MessagePusher.pushMessage(session, respRoleInfo);
            }
        } else {
            PlayerProfile playerProfile = SpringUtils.getPlayerService().queryPlayerProfile(uid);
            RespOfflineCharInfo respOfflineCharInfo = new RespOfflineCharInfo();
            respOfflineCharInfo.setMsgType(reqCheckPlayer.getDlg_type());
            respOfflineCharInfo.setGid(String.valueOf(playerProfile.getGid()));
            respOfflineCharInfo.setName(playerProfile.getName());
            respOfflineCharInfo.setLevel(playerProfile.getLevel());
            respOfflineCharInfo.setIcon(playerProfile.getRoleIcon());
            MessagePusher.pushMessage(session, respOfflineCharInfo);
        }
    }

    /**
     * 查看玩家装备
     *
     * @param role
     * @param reqGeneralNotify
     */
    public Message checkRoleInfo(Role role, ReqGeneralNotify reqGeneralNotify) {
        long uid = Long.parseLong(reqGeneralNotify.getStatus());
        Role checkRole = SpringUtils.getRoleService().getOnlinePlayer(uid);
        if (checkRole == null) {
            MessagePusher.pushMessage(role, new RespMsg("目标玩家不在线，无法查看。"));
            return null;
        }
        Map<String, Integer> setMap = role.getExtendBox().getSetMap();
        if (setMap.getOrDefault("refuse_look_equip", 0) == 1) {
            RespMsg respMsg = new RespMsg("目标玩家已关闭装备查看。");
            MessagePusher.pushMessage(role, respMsg);
            return respMsg;
        }

        RespRoleAllInfo respRoleAllInfo = new RespRoleAllInfo();
        respRoleAllInfo.setEffects(new ArrayList<>());
        respRoleAllInfo.setIcon(checkRole.getRoleIcon());
        respRoleAllInfo.setLevel(checkRole.getLevel());
        respRoleAllInfo.setList(new ArrayList<>());
        respRoleAllInfo.setFlyUpEffect((byte) 0);// 飞升特效
        respRoleAllInfo.setName(checkRole.getName());
        respRoleAllInfo.setPartyName(checkRole.getPartyName());
        respRoleAllInfo.setShineIcon(checkRole.getSuitLightId());
        respRoleAllInfo.setSuitIcon(checkRole.getSuitId());
        respRoleAllInfo.setWeaponIcon(checkRole.getWeaponIcon());
        respRoleAllInfo.setYuanYinglevel((short) 0);
        respRoleAllInfo.setFasionIcon(checkRole.getFasionIcon());
        if (checkRole.isCustom()) {
            if (!Strings.isEmpty(checkRole.getCustomFasion())) {
                if (checkRole.getGender() == 1) {
                    respRoleAllInfo.setFasionIcon(61001);
                } else {
                    respRoleAllInfo.setFasionIcon(60001);
                }
                respRoleAllInfo.setCustomFasion(checkRole.getCustomFasion());
            }
        }

        for (Byte equipPos : Const.MAIN_PAGE) {
            RoleEquip roleEquip = equipService.getRoleEquipByPos(checkRole, equipPos);
            if (roleEquip == null) {
                continue;
            }
            RoleEquipInfos roleEquipInfos = new RoleEquipInfos();
            roleEquipInfos.setPosition(roleEquip.getPosition());
            roleEquipInfos.setEquipFields(equipService.transferList(roleEquip.getFields()), equipService.transferList2(roleEquip.getHunQiFields()));
            respRoleAllInfo.getList().add(roleEquipInfos);
        }

        MessagePusher.pushMessage(role, respRoleAllInfo);
        return respRoleAllInfo;
    }

    /**
     * 换线
     */
    public void changeLine(IoSession session, ReqSwitchLine reqSwitchLine) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        Server result = null;
        Server currServer = null;
        Server areaServer = serverService.getServer();
        for (Server server : DataCache.ID_SERVER.values()) {
            if (!(server.getIp().equals(areaServer.getIp()) && server.getPort() == areaServer.getPort())) {
                continue;
            }
            if (server.getSonName().equals(reqSwitchLine.getLineName())) {
                result = server;
            }
            if (serverService.getPort() == server.getSonPort()) {
                currServer = server;
            }
        }
        if (currServer == null || result == null) {
            return;
        }
        if (!serverService.isLocal() && currServer.getSonName().equals(reqSwitchLine.getLineName())) {
            return;
        }
        // 判断另外一个线是否满人
        RespSwitchServer respSwitchServer = new RespSwitchServer();
        respSwitchServer.setResult((short) 1);
        respSwitchServer.setContent(result.getSonIp() + "," + result.getSonPort() + ",15738245,1788328796," + role.getName());

        MessagePusher.pushMessage(session, respSwitchServer);
    }

//    /**
//     * 取角色所在线路
//     *
//     * @param uid
//     * @return
//     */
//    public NutMap getOnlineStatusById(long uid) {
//        return DataCache.ONLINE_STATUS.getOrDefault(uid, new NutMap());
//    }

//    /**
//     * 修改角色所在线路
//     */
//    public void alterOnlineStatus(long uid, boolean online, String lineName) {
//        NutMap nutMap = DataCache.ONLINE_STATUS.computeIfAbsent(uid, k -> NutMap.NEW());
//        nutMap.setv("lineName", lineName);
//    }

    /**
     * 刷新角色面板 TODO 注意 这个不能单独发 必须用增益那个发 否则属性显示异常
     */
    public void refreshRole(Role member) {
        List<FiedValue> values = FieldUtils.rolePanelInfo(member);
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(member.getRoleId());
        respUpdate.setList(values);

        MessagePusher.pushMessage(member, respUpdate);
    }


    public void sendupdatemijingjifen(Role role) {
        List<FiedValue> list = new ArrayList();
        list.add(new FiedValue(488, role.getMijingjifen()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage((Role)role, respUpdate);
    }
    /**
     * 增加奇门秘境积分
     */
    public void addmijingjifen(Role role, int mijingjifen) {
        if (mijingjifen < 0) {
            throw new IllegalArgumentException("增加秘境积分不能为负数");
        } else {
            int newScore = role.getMijingjifen() + mijingjifen;
            if (newScore > 600000000) {
                newScore = 600000000;
            }

            role.setMijingjifen(newScore);
            role.save();
            MessagePusher.pushMessage((Role)role, new RespNotifyMiscEx("获得#R" + mijingjifen + "#n秘境积分"));
            this.sendupdatemijingjifen(role);
        }
    }

    public void submijingjifen(Role role, int count, boolean send) {
        if (count > 0) {
            role.setMijingjifen(role.getMijingjifen() - count);
            role.save();
            if (send) {
                this.sendupdatemijingjifen(role);
            }

        }
    }
    public void Sendupdatehaoxianzhijifen(Role role) {
        List<FiedValue> list = new ArrayList();
        list.add(new FiedValue(37, role.getNice()));
        list.add(new FiedValue(313, role.getNiceszhi()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage((Role)role, respUpdate);
    }

    public void submihaoxianzhi(Role role, int count, boolean send) {
        if (count > 0) {
            role.setNice(role.getNice() - count);
            role.save();
            if (send) {
                this.Sendupdatehaoxianzhijifen(role);
            }

        }
    }

    public void addhaoxianzhi(Role role, int haoxianzhi) {
        if (haoxianzhi < 0) {
            throw new IllegalArgumentException("增加好心值不能为负数");
        } else {
            int newScore = role.getNice() + haoxianzhi;
            if (newScore > Integer.MAX_VALUE) {
                newScore = Integer.MAX_VALUE;
            }

            int rehaoxianzhi = role.getNiceszhi() - haoxianzhi;
            if (rehaoxianzhi > Integer.MAX_VALUE) {
                rehaoxianzhi = Integer.MAX_VALUE;
            }

            role.setNiceszhi(rehaoxianzhi);
            role.setNice(newScore);
            role.save();
            MessagePusher.pushMessage((Role)role, new RespNotifyMiscEx("获得#R" + haoxianzhi + "#n好心值"));
            this.Sendupdatehaoxianzhijifen(role);
        }
    }
    public void refreshRoleBasic(Role member) {
        List<FiedValue> values = FieldUtils.roleShuxin(member);
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(member.getRoleId());
        respUpdate.setList(values);
        MessagePusher.pushMessage(member, respUpdate);
    }

    /**
     * 是否已经开启对应类型功能
     */
    public boolean isOpenFunction(Role role, FunctionType functionType) {
        RoleFunction funcs = role.getFuncs();
        return funcs.isOpen(functionType.getFunctionId());
    }

    /**
     * 对玩家进行重置操作检测
     */
    public void checkReset(Role role) {
        /** 登录的时候检查每日重置 */
        checkDailyFiveReset(role);
        /** 登录的时候检查每月重置 */
        checkWeeklyReset(role);
        /** 登录的时候检查每月重置 */
        checkMonthReset(role);
    }

    /**
     * 对玩家进行每日5点重置操作
     */
    public void checkDailyFiveReset(Role role) {
        /** 判断是否可以重置 */
        if (!isCanDailyFiveReset(role)) {
            log.info("不能进行每日5点重置，角色ID: {}, 上一次重置时间戳：{}", role.getRoleId(),
                    role/* .getReset() */.getDailyFiveResetTime());
            return;
        }

        doDailyFiveReset(role);
    }

    public AjaxResult doDailyFiveResetForAll(){
        String sql = "select sid, roleId, uid, `name`, distName, roleIcon, `level`, polar,enterTime from t_role";
        List<PlayerProfile> profileList = SpringUtils.getBean(JdbcTemplate.class).query(sql, new PlayerRowMapper());
        log.info("预重置玩家数量=={}", profileList.size());
        PlayerService  playerService = SpringUtils.getBean(PlayerService.class);
        int i = 0;
        for (PlayerProfile playerProfile : profileList) {
            i +=1;
            try{
                Role role = playerService.getPlayerBy(playerProfile.getGid());
                doDailyFiveReset(role);
                log.info("重置玩家第"+i+"个："+role.getName());
            }catch(Exception e){
                log.info("aa",e);
                log.info("重置玩家任务出错："+playerProfile.getName());
            }
        }
        log.info("实际处理玩家数量=={}", i);
        return  AjaxResult.success();
    }

    private class PlayerRowMapper implements RowMapper<PlayerProfile> {

        @Override
        public PlayerProfile mapRow(ResultSet re, int arg1) throws SQLException {
            return new PlayerProfile(re.getString("sid"), re.getInt("roleId"), re.getLong("uid"), re.getString("name"),
                    re.getString("distName"), re.getShort("roleIcon"),
                    re.getShort("level"),
                    re.getShort("polar"), re.getLong("enterTime"));
        }

    }
    /**
     * 进行每日12点重置 累计充值记录
     */
    public void doDailyFiveReset2(Role role) {
        role.getExtendBox().getMrTotalContent().clear();
    }
    /**
     * 进行每日5点重置
     */
    public void doDailyFiveReset(Role role) {
        log.info("玩家{}进行每日5点重置，上一重置时间为{}", role.getRoleId(), role/* .getReset() */.getDailyFiveResetTime());

        /** 更新重置时间为当前时间 */
        role/* .getReset() */.setDailyFiveResetTime(System.currentTimeMillis());

        SpringUtils.getBean(ActivityService.class).dailyResetActivity(role);
        dailyResetVip(role);
        try{
            SpringUtils.getBean(NewTaskService.class).dailyResetTask(role);
        }catch(Exception e){
            log.info("出错{}",e);
        }
        /**重置首饰强化*/
        role.setJewelryStrengthenCount(0);
        sendExtraAttribute(role);

        SpringUtils.getBean(DropService.class).dailyReset(role);
        /**重置在线时长*/
        resetOnlineSec(role);
        /**每日重置时登录天数+1*/
        role.setLoginDays(role.getLoginDays() + 1);
        // 重置 成长秘籍的每日任务
        PlayerCzmjInfo playerCzmjInfo = role.getExtendBox().getPlayerCzmjInfo();
        playerCzmjInfo.setCzmjTask(new ArrayList<>());

        /**5点重置的时候检测安全锁重置*/
        SpringUtils.getBean(SafeService.class).checkSafePasswdReset(role);

        SpringUtils.getBean(StatsService.class).dailyReset(role);

        SpringUtils.getBean(OnlineRewardHandler.class).setOnlineRewardSec(role);

        SpringUtils.getBean(ShiDaoHandler.class).dailyReset(role);

        role.setJuntianJson(null);  //重置九天真君
        ((ZhenMoLuService)SpringUtils.getBean(ZhenMoLuService.class)).resetZM(role);//镇魔录
        MSGJiuTianRespMasterInfo Info = role.getMsgjuntian();
        Info.setCurCheckpoint((byte)0);
        Info.setOpenMax((byte)1);
        Info.setIndex((byte)0);
        role.save();
        log.info("玩家{}进行每日5点重置，上一重置时间为{}", role.getRoleId(), role/* .getReset() */.getDailyFiveResetTime());
    }

    /**
     * 重置会员领取状态
     */
    private void dailyResetVip(Role role) {
        /** 更新VIP领取银元宝状态 */
        role.setReceive(false);

        RespVipStatus RespVipStatus = new RespVipStatus(); // 会员状态
        RespVipStatus.setType(role.getVipType());
        RespVipStatus.setExpireTime(role.getExpireTime());
        RespVipStatus.setReceive(role.isReceive());
        MessagePusher.pushMessage(role, RespVipStatus);
    }

    /**
     * 能否进行每日5点重置
     */
    private boolean isCanDailyFiveReset(Role role) {
        /** 现在记录的是上一次重置时间 */
        long dailyFiveResetTime = role/* .getReset() */.getDailyFiveResetTime();
        Calendar roleResetCalader = Calendar.getInstance();
        roleResetCalader.setTimeInMillis(dailyFiveResetTime);

        /** 玩家上一重置时间在重置时间之前的，则重置 */
        Calendar systemResetTime = getSystemFiveResetTime();
        return roleResetCalader.before(systemResetTime);
    }

    /**
     * 获得系统5点重置的时间
     */
    private Calendar getSystemFiveResetTime() {
        Calendar calendar = Calendar.getInstance();
        /**当前小时小于重置的小时，拿前一天*/
        if (calendar.get(Calendar.HOUR_OF_DAY) < Const.RESET_HOUR) {
            calendar.add(Calendar.DAY_OF_YEAR, -1);
        }
        calendar.set(Calendar.HOUR_OF_DAY, Const.RESET_HOUR);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar;
    }

    /**
     * 对玩家进行每月重置操作
     */
    public void checkMonthReset(Role role) {
        /** 判断是否可以重置 */
        if (!isCanMonthReset(role)) {
            log.info("不能进行每月重置，角色ID: {}, 上一次重置时间戳：{}", role.getRoleId(),
                    role.getMonthResetTime());
            return;
        }

        doMonthReset(role);
    }

    private boolean isCanMonthReset(Role role) {
        /** 现在记录的是上一次重置时间 */
        long monthResetTime = role.getMonthResetTime();
        Calendar roleResetCalader = Calendar.getInstance();
        roleResetCalader.setTimeInMillis(monthResetTime);

        /** 玩家上一重置时间在重置时间之前的，则重置 */
        Calendar systemResetTime = getSystemMonthResetTime();
        return roleResetCalader.before(systemResetTime);
    }

    /**
     * 获得系统每月重置的时间
     */
    public Calendar getSystemMonthResetTime() {
        /**每月1日0点0分 每月重置*/
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

    /**
     * 进行每月重置
     */
    public void doMonthReset(Role role) {
        log.info("玩家{}进行每月重置，上一重置时间为{}", role.getRoleId(), role.getMonthResetTime());

        role.setMonthResetTime(System.currentTimeMillis());

        /*resetMonthTao(role);
        resetPetMonthWuxue(role);*/
    }

    /**
     * 重置月道行
     */
    private void resetMonthTao(Role role) {
        long monthTao = role.getMonthTaoPoint();
        role.setMonthTaoPoint(0);
        role.setPrevMonthTaoPoint(monthTao);
    }

    /**
     * 重置宠物月武学
     */
    private void resetPetMonthWuxue(Role role) {
        List<Pet> pets = SpringUtils.getPetService().getPetList(role);
        if (pets == null) {
            return;
        }

        for (Pet pet : pets) {
            int monthMartial = pet.getMonthMartial();
            pet.setMonthMartial(0);
            pet.setPrevMonthMartial(monthMartial);
        }
    }

    /**
     * 对玩家进行每周重置操作
     */
    public void checkWeeklyReset(Role role) {
        /** 判断是否可以重置 */
        if (!isCanWeeklyReset(role)) {
            log.info("不能进行每周重置，角色ID: {}, 上一次重置时间戳：{}", role.getRoleId(),
                    role.getWeeklyResetTime());
            return;
        }

        doWeeklyReset(role);
    }

    private boolean isCanWeeklyReset(Role role) {
        /** 现在记录的是上一次重置时间 */
        long weeklyResetTime = role.getWeeklyResetTime();
        Calendar roleResetCalader = Calendar.getInstance();
        roleResetCalader.setTimeInMillis(weeklyResetTime);

        /** 玩家上一重置时间在重置时间之前的，则重置 */
        Calendar systemResetTime = getSystemWeeklyResetTime();
        return roleResetCalader.before(systemResetTime);
    }

    /**
     * 获得系统每周重置的时间
     */
    public Calendar getSystemWeeklyResetTime() {
        /**每周一 5点0分 每周重置*/
        Calendar calendar = Calendar.getInstance();
        /**小于周一或者周一且当前小时小于重置的小时，拿前一周*/
        if (calendar.get(Calendar.DAY_OF_WEEK) < Calendar.MONDAY
                || (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY && calendar.get(Calendar.HOUR_OF_DAY) < Const.RESET_HOUR)) {
            calendar.add(Calendar.DAY_OF_YEAR, -7);
        }
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY, Const.RESET_HOUR);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }

    /**
     * 进行每周重置
     */
    public void doWeeklyReset(Role role) {
        log.info("玩家{}进行每周重置，上一重置时间为{}", role.getRoleId(), role.getWeeklyResetTime());

        role.setWeeklyResetTime(System.currentTimeMillis());
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, 5);
        cal.set(Calendar.MINUTE, 0);
        cal.add(Calendar.DAY_OF_MONTH, -1); //解决周日会出现 并到下一周的情况
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        //重置成长秘籍
        PlayerCzmjInfo playerCzmjInfo  = new PlayerCzmjInfo();
        playerCzmjInfo.setStartTime((int)(cal.getTimeInMillis()/1000));
        playerCzmjInfo.setEndTime((int)(cal.getTimeInMillis()/1000+3600*24*7));
        role.getExtendBox().setPlayerCzmjInfo(playerCzmjInfo);
        /**月道行和月武学改为每周重置*/
        resetMonthTao(role);
        resetPetMonthWuxue(role);
    }

    /**
     * 把玩家加入到在线列表
     */
    public void addOnline(Role role) {
        if (role == null) {
            return;
        }
        Account account = accountService.getAccount(role.getSid());
        if (account != null && account.getPrivilege() >= 200) {
            DataCache.ONLINE_GM.put(role.getUid(), role);
        }
        DataCache.ONLINE_ROLES.put(role.getUid(), role);
    }

    /**
     * 把玩家从在线列表移除
     */
    public void removeOnline(Role role) {
        if (role == null) {
            return;
        }
        role.setOn_line(0);
        role.save();
       log.info(role.getName()+"下线了。");
        DataCache.ONLINE_ROLES.remove(role.getUid());
    }

    public boolean isOnline(Role role) {
        return DataCache.ONLINE_ROLES.containsKey(role.getUid());
    }

    public boolean isOnline(long roleUid) {
        return DataCache.ONLINE_ROLES.containsKey(roleUid);
    }

    public boolean isOnline(int roleId) {
        long uid = SpringUtils.getPlayerService().getUidBy(roleId);
        return isOnline(uid);
    }

    /**
     * 初始化升级需要经验
     */
    public void initUpgradeNeedExp(List<RoleExp> list) {
        list.forEach(exp -> RoleDataPool.level2RoleExp.put(exp.getLevel(), exp));
    }

    /**
     * 初始化宠物的经验配置
     */
    public void initPetUpgradeNeedExp(List<PetExp> petExps) {
        petExps.forEach(petExp -> RoleDataPool.level2PetExp.put(petExp.getLevel(), petExp));
    }

    /**
     * 死亡提升界面
     */
    public void sendDeadRemind(Role role) {
        RespGeneralNotify notify = new RespGeneralNotify();
        notify.setNotify(NotifyModules.NOTIFY_OPEN_DLG);
        notify.setValue("DeadRemindDlg");
        MessagePusher.pushMessage(role, notify);
    }

    /**
     * 增加元宝
     */
    public void addGold(Role role, int gold, Reason reason) {
        if (gold <= 0) {
            return;
        }
        String tips = "#R" + gold + "#n金元宝";
        addRewardTips(role, tips, false);
        MessagePusher.pushMessage(role, new RespNotifyMisc("获得" + tips + "。"));
        Account account = SpringUtils.getAccountService().getAccount(role.getSid());
        long oldgold = account.getGold();
        if (oldgold + gold > 2000000000) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("元宝超过#R20亿#n，已将元宝放入#R珍宝#n中！！！"));
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("元宝超过#R20亿#n，已将元宝放入#R珍宝#n中！！！"));
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("元宝超过#R20亿#n，已将元宝放入#R珍宝#n中！！！"));
            role.setStallGold(gold + role.getStallGold());
        } else {
            account.addGold(gold, reason);
        }
        Db4CommonService.getInstance().add2Queue(account);
        updateRoleGoldAndSiver(role);
    }

    /**
     * 增加判断是扣除元宝还是积分
     */
    public void subGoldOrCharge(Role role, int count, Reason reason) {
        //扣除元宝
        if(Const.systemType ==1){
            subtractGold( role,  count,  reason);
        }else{
            substractChargeScore(role, count);
        }
    }

    /**
     * 增加判断是扣除元宝还是积分
     */
    public void subCountByteType(Role role, int count,String type) {
        //扣除元宝
        if("元宝".equals(type)){
            subtractGold( role,  count,  Reason.BUY_ITEM);
        }else if("积分".equals(type)){
            substractChargeScore(role, count);
        }else{
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("配置错误。请联系GM"));
            throw new IllegalArgumentException("配置错误！");
        }
    }

    /**
     * 增加判断是增加元宝还是积分
     */
    public void addCountByteType(Role role, int count,String type) {
        //扣除元宝
        if("元宝".equals(type)){
            addGold(role,count,Reason.CHOU_JIANG);
        }else if("积分".equals(type)){
            addRechargeScore(role,count);
        }else{
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("配置错误。请联系GM"));
            throw new IllegalArgumentException("配置错误！");
        }
    }


    /**
     * 扣除元宝
     */
    public void subtractGold(Role role, int gold, Reason reason) {
        if (gold <= 0) {
            return;
        }
        Account account = SpringUtils.getAccountService().getAccount(role.getSid());
        if( account.costGold(gold, reason)){
            Db4CommonService.getInstance().add2Queue(account);
            updateRoleGoldAndSiver(role);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("扣除#R" + gold + "元宝#n成功。"));
        }else{
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("元宝不足，扣除#R" + gold + "元宝#n失败！！"));
            throw new IllegalArgumentException("元宝不足#R"+gold);
        }
    }

    /**
     * 减少阴德
     *
     * @param role
     * @param yinde
     */
    public void subYinde(Role role, int yinde, boolean send) {
        if (yinde <= 0) {
            return;
        }

        HunPoProp prop = hunPoService.getHunPoProp(role);
        prop.setYinDe(Math.max(0, prop.getYinDe() - yinde));
        role.save();
        log.error("减少阴德=={}=={}=={}=={}", role.getRoleId(), role.getName(), yinde, prop.getYinDe());
        if (send) {
            sendYinDe(role);
        }
    }
    /**
     * 增加鬼气
     */
    public void addGuiQi(Role role,int count,boolean send){
        if (count <= 0) {
            return;
        }
        role.setGuiqi(role.getGuiqi()+count); ;
        role.save();
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("增加鬼气#R" + count + "点"));
        if(send){
            sendUpdatePeiYuanStage(role);
        }
    }
    /**
     * 减少鬼气
     */
    public void subGuiQi(Role role,int count,boolean send){
        if (count <= 0) {
            return;
        }
        role.setGuiqi(role.getGuiqi()-count); ;
        role.save();
        if(send){
            sendUpdatePeiYuanStage(role);
        }
    }


    /**
     * 减少武灵值
     *
     * @param role
     * @param yinde
     */
    public void subWuling(Role role, int Wuling, boolean send) {
        if (Wuling <= 0) {
            return;
        }

        WuHunPoProp prop = WWuHunService.getWuHunPoProp(role);
        prop.setWulingzhi(Math.max(0, prop.getWulingzhi() - Wuling));
        role.save();
        log.error("减少武灵值=={}=={}=={}=={}", role.getRoleId(), role.getName(), Wuling, prop.getWulingzhi());
        if (send) {
            sendYinDe(role);
        }
    }

    /**
     * 增加武灵值
     *
     * @param role
     * @param score
     */
    public void addWuling(Role role, int score, boolean send) {
        if (score <= 0) {
            return;
        }

        WuHunPoProp prop = WWuHunService.getWuHunPoProp(role);
        prop.setWulingzhi(Math.min(WWuHunService.MAX_WKZ_DE, prop.getWulingzhi() + score));
        role.save();
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("增加武灵值#R" + score + "点"));
        log.error("增加武灵值=={}=={}=={}=={}", role.getRoleId(), role.getName(), score, prop.getWulingzhi());
        sendUpdateWuhun(role);

    }



    /**
     * 增加阴德
     *
     * @param role
     * @param score
     */
    public void addYinde(Role role, int score, boolean send) {
        if (score <= 0) {
            return;
        }

        HunPoProp prop = hunPoService.getHunPoProp(role);
        prop.setYinDe(Math.min(HunPoService.MAX_YIN_DE, prop.getYinDe() + score));
        role.save();
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("增加阴德#R" + score + "点"));
        log.error("增加阴德=={}=={}=={}=={}", role.getRoleId(), role.getName(), score, prop.getYinDe());
        if (send) {
            sendYinDe(role);
        }
    }

    public void sendYinDe(Role role) {
        sendUpdateShenHunStage(role);
    }

    /**
     * 发送神魂
     *
     * @param role
     */
    public void sendUpdateShenHunStage(Role role) {
        List<FiedValue> list = new ArrayList<>();
        HunPoProp hunPoProp = hunPoService.getHunPoProp(role);
        list.add(new FiedValue(0x01D5, hunPoProp.getLevel() >= 10 ? 10 : hunPoProp.getLevel()));//神魂阶
        list.add(new FiedValue(0x01D6, hunPoProp.getLevelInner()));//神魂子阶
        list.add(new FiedValue(0x01D7, 3, hunPoProp.getYinDe()));//阴魂
        list.add(new FiedValue(0x01D8, hunPoService.getStageUpReq(hunPoProp.getLevel(), hunPoProp.getLevelInner())));//升级需要
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
//        log.error("神魂发送=={}",Json.toJson(respUpdate));
    }

    /**
     * 发送培元
     *
     * @param role
     */
    public void sendUpdatePeiYuanStage(Role role) {
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(0x03C0,role.getGuiqi()));
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
//        log.error("神魂发送=={}",Json.toJson(respUpdate));
    }

    /**
     * 发送武魂
     *
     * @param role
     */
    public void sendUpdateWuhun(Role role) {
        List<FiedValue> list = new ArrayList<>();
        WuHunPoProp wuHunPoProp = WWuHunService.getWuHunPoProp(role);
        int lc = wuHunPoProp.getLevel();
        int jc =(lc-1)*100;
        list.add(new FiedValue(495, 3,jc+wuHunPoProp.getLevelInner()));//wuhun_data/level
        list.add(new FiedValue(496, 3,wuHunPoProp.getWulingzhi()));//wuhun_data/exp
        list.add(new FiedValue(497, 3,WWuHunService.getStageUpReq(wuHunPoProp.getLevel(), wuHunPoProp.getLevelInner())));//exp_to_next_level
        list.add(new FiedValue(498, 3,0));//whzc_num
        list.add(new FiedValue(499, 3,0));//wuhunqiao_page

        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
//        log.error("神魂发送=={}",Json.toJson(respUpdate));
    }
    /**
     * 发送内丹
     *
     * @param role
     */
    public void sendUpdateNeiDanStage(Role role,NeidanProp neidanProp) {
        List<FiedValue> list = new ArrayList<>();
        list.add(new FiedValue(439, neidanProp.getState()));//内丹阶
        list.add(new FiedValue(440, neidanProp.getStage()));//内丹子阶
        list.add(new FiedValue(441, neidanProp.getExp()));//积分
        list.add(new FiedValue(442, neidanProp.getExpToNextLevel()));//下一级积分
        list.add(new FiedValue(443,neidanProp.getTotalAttribPoint()));//累计属性
        list.add(new FiedValue(444, neidanProp.getTotalPolarPoint()));//累计相性
        list.add(new FiedValue(445, 100));//阴魂
        list.add(new FiedValue(446, 100));//阴魂
        list.add(new FiedValue(447, neidanProp.getTodayExp()));//阴魂
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);
        MessagePusher.pushMessage(role, respUpdate);
//        log.error("神魂发送=={}",Json.toJson(respUpdate));
    }


    /**
     * 阴德
     *
     * @param role
     * @param score
     */
    public void yinde(Role role, int score) {
        if (score > 0) {
            addYinde(role, score, true);
        } else {
            subYinde(role, -1 * score, true);
        }
    }

    /**
     * 发送刷道道具状态
     */
    public void sendShuadaoStauts(Role role) {
        RespShuadaoRefresh respShuadaoRefresh = new RespShuadaoRefresh();
        respShuadaoRefresh.setZiqihongmeng_status((short) role.getPropsStatus().getInt("ziqiStatus", 0));
        respShuadaoRefresh.setChongfengsan_status((short) role.getPropsStatus().getInt("petStatus", 0));
        respShuadaoRefresh.setJijiStatus((short) role.getPropsStatus().getInt("manguaiStatus", 0));
//        /**刷道降妖、伏魔、飞仙渡邪的十轮耗时*/
        ShuaDaoTaskHandler shuaDaoTaskHandler = SpringUtils.getBean(ShuaDaoTaskHandler.class);
        respShuadaoRefresh.setXiangyanoTime(shuaDaoTaskHandler.getTenShuaDaoUsedTime(role, ActivityType.SHUA_DAO_XIANGYAO_TASK));
//        respShuadaoRefresh.setXiangyanoTime((short) 999);
        respShuadaoRefresh.setFomoTime(shuaDaoTaskHandler.getTenShuaDaoUsedTime(role, ActivityType.SHUA_DAO_FUMO_TASK));
//        respShuadaoRefresh.setFomoTime((short) 800);
        respShuadaoRefresh.setFeixianTime(shuaDaoTaskHandler.getTenShuaDaoUsedTime(role, ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK));
//        respShuadaoRefresh.setFeixianTime((short) 700);
//        respShuadaoRefresh.setMax_buy_time((short) 99);

        respShuadaoRefresh.setFomoTime_2(shuaDaoTaskHandler.getTenShuaDaoUsedTime(role, ActivityType.SHUA_DAO_FUMO_TASK2));

        respShuadaoRefresh.setFeixianTime_2(shuaDaoTaskHandler.getTenShuaDaoUsedTime(role, ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK2));
        respShuadaoRefresh.setList(new ArrayList<>());
        respShuadaoRefresh.setBuy_five(role.getOfflineNotice().getOfflineTime());//拥有的离线刷道时间
        respShuadaoRefresh.setOfflineStatus((short) role.getOfflineNotice().getShuadao());
        RoleOfflineNotice offlineNotice = role.getOfflineNotice();
        if (offlineNotice.getActivityType() != null) {
            if (offlineNotice.getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_XIANGYAO_TASK.getActivityId()) || offlineNotice.getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_XIANGYAO_TASK2.getActivityId())) {
                respShuadaoRefresh.setLastTaskName("降妖");
            } else if (offlineNotice.getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FUMO_TASK.getActivityId()) || offlineNotice.getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FUMO_TASK2.getActivityId())) {
                respShuadaoRefresh.setLastTaskName("伏魔");
            } else if (offlineNotice.getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK.getActivityId()) || offlineNotice.getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK2.getActivityId())) {
                respShuadaoRefresh.setLastTaskName("飞仙渡邪");
            }
        }
        int lastround = getLastRound(role);
        respShuadaoRefresh.setRound((short) lastround);// 剩余轮数
        if (lastround < role.getOfflineNotice().getRound()) {
            respShuadaoRefresh.setHasBonus((short) 1);
        } else {
            respShuadaoRefresh.setHasBonus((short) 0);
        }
//        {0.
//            ShuadaoValue shuadaoValue = new ShuadaoValue();
//            shuadaoValue.setName("降妖");
//            shuadaoValue.setA((short) 4);
//            respShuadaoRefresh.getList().add(shuadaoValue);
//        }
//        log.error("刷道数据=={}=={}",Json.toJson(respShuadaoRefresh));
        MessagePusher.pushMessage(role, respShuadaoRefresh);
    }

    public short getLastRound(Role role) {
        ShuaDaoTaskHandler shuaDaoTaskHandler = SpringUtils.getBean(ShuaDaoTaskHandler.class);
        RoleOfflineNotice offlineNotice = role.getOfflineNotice();
        int ten = shuaDaoTaskHandler.getTenShuaDaoUsedTime(role, offlineNotice.getActivityType());
//        log.error("计算剩余轮数=={}==",ten);
//        if (ten < 160){
//            ten = 600;
//        }
        ten = ten * 1000;
        ten = ten / 10;
        long cost = System.currentTimeMillis() - offlineNotice.getLastTime() - 2 * TimeUtil.ONE_MINUTE;
        long leiji = offlineNotice.getLeijiTime() + (cost > 0 ? cost : 0);
        if (ten <= 0) {
            return (short) offlineNotice.getRound();
        }
        // 累计的时间超过当前购买的时间，用当前购买的时间
        if (leiji / 1000 > role.getOfflineNotice().getOfflineTime()) {
            leiji = role.getOfflineNotice().getOfflineTime() * 1000;
        }
        long costround = leiji / ten;
        long lastround = (offlineNotice.getRound() - costround);
//        log.error("计算剩余轮数=={}=={}=={}=={}=={}=={}",cost,leiji,ten,costround,lastround);
        return lastround <= 0 ? (short) 0 : (short) lastround;
    }

    /**
     * 战斗死亡惩罚
     */
    public void punishFightDead(Role role) {
        if (role.getLastDead() != 0) {
//            try {
//                throw new IllegalArgumentException("死亡惩罚");
//            }catch (Exception e){
//            log.error("死亡惩罚打印==={}=={}",role.getRoleId(),role.getName(),e);
//            }
            return;
        }
        role.setLastDead(1);
        /**判断是否有免死亡惩罚死次数，有则只扣次数，不进行惩罚*/
        /**红名状态时，免死亡惩罚不生效*/
        if (!role.getPkInfoBox().isRedName() && role.getNoDeath() > 0) {
            godProtect(role);
        } else {
            doPunishFightDead(role);

            /**非红名状态时减少PK值*/
            if (!role.getPkInfoBox().isRedName()) {
                substractForcePkValue(role, 1);
            }
        }
        /**死亡提升界面*/
        sendDeadRemind(role);
    }

    /**
     * 天神护佑生效
     */
    private void godProtect(Role role) {
        if (role.getNoDeath() <= 0) {
            return;
        }

        role.setNoDeath((short) (role.getNoDeath() - 1));
        role.save();
        log.error("扣除免死次数");

        /**更新任务*/
        if (role.getNoDeath() <= 0) {
            SpringUtils.getBean(GodProtectTaskHandler.class).resetTask(role);
        } else {
            SpringUtils.getBean(GodProtectTaskHandler.class).pushTask(role);
        }

        String msg = "你得到了天神的护佑，免去了#R1#n次死亡惩罚，当前还可以免去#R{0}#n次死亡惩罚";
        MessagePusher.pushMessage(role, new RespNotifyMiscEx(MessageFormat.format(msg, role.getNoDeath())));
    }

    private void doPunishFightDead(Role role) {
        StringBuilder msg = new StringBuilder();
        /**经验扣5%，可以变成负数*/
//        int subExp = (int) (getRoleUpgradeNeedExp(role.getLevel()) * 5 / 100);
//        if (subExp > 0) {
//            substractExp(role, subExp);
//            msg.append(MessageFormat.format("#R{0}#n点经验", subExp));
//        }
//
//        /**金钱扣20%*/
//        int subMoney = role.getMoney() * 20 / 100;
//        if (subMoney > 0) {
//            subtractMoney(role, subMoney);
//            if (msg.length() > 0) {
//                msg.append("，");
//            }
//            msg.append(MessageFormat.format("#R{0}#n文钱", subMoney));
//        }

        /**道行扣标准道行1%*/
//        double stdTao = FormulaUtil.getStdTao(role.getLevel());
        int subDaohang = 5 * 365;
        if (subDaohang > 0) {
            substractTao(role, subDaohang);
            if (msg.length() > 0) {
                msg.append("，");
            }
//            msg.append(MessageFormat.format("{0}道行", AsktaoUtil.getFormatTao(subDaohang*Const.ONE_DAY_POINT)));
        }

//        if (msg.length() > 0) {
//            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你死亡了，因此损失了" + msg.toString() + "。"));
//        }

        /**产生一个死亡惩罚事件*/
        EventDispatcher.getInstance().fireEvent(new DeadPunishEvent(EventType.DEAD_PUNISH, role));
    }

    /**
     * 扣除经验
     */
    public void substractExp(Role role, int exp) {
        if (exp <= 0) {
            return;
        }

        /**扣除*/
        role.setExp(role.getExp() - exp);
        role.save();

        /**更新面板*/
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(Collections.singletonList(new FiedValue(25, role.getExp())));
        MessagePusher.pushMessage(role, respUpdate);

        /**产生一个人物经验变化事件*/
        EventDispatcher.getInstance().fireEvent(new RoleExpChangeEvent(EventType.ROLE_EXP_CHANGE, role, -exp));
    }

    /**
     * 扣除道行
     */
    public void substractTao(Role role, int subTao) {
        if (subTao <= 0) {
            return;
        }
        long oldTaoPoint = role.getTaoPoint();
        long sub = new Long(subTao) * Const.ONE_DAY_POINT;
        if (sub >= 2000000000) {
            sub = 2000000000;
        }
        role.setTaoPoint(role.getTaoPoint() - sub);
        if (role.getTaoPoint() < subTao * Const.ONE_DAY_POINT) {
            role.setTaoPoint(0);
        }
        role.save();

        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(Collections.singletonList(new FiedValue(20, role.getTao())));
        respUpdate.setList(Collections.singletonList(new FiedValue(175, role.getTaoLastPoint())));
        MessagePusher.pushMessage(role, respUpdate);

        if (role.getTaoPoint() != oldTaoPoint) {
            /**产生一个道行变化事件*/
            EventDispatcher.getInstance().fireEvent(new TaoChangeEvent(EventType.TAO_CHANGE, role, role.getTao(), oldTaoPoint - role.getTaoPoint()));
        }
        StringBuilder msg = new StringBuilder();
        msg.append(MessageFormat.format("{0}道行", AsktaoUtil.getFormatTao((int) sub)));
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("减少了" + msg.toString() + "。"));
    }

    /**
     * 回到出生点
     */
    public void goBackBorn(Role role) {
        Pos pos = new Pos();
        ReqTelePort reqTelePort = new ReqTelePort();
        reqTelePort.setMapId(pos.getMapId());
        reqTelePort.setX(pos.getX());
        reqTelePort.setY(pos.getY());
        SpringUtils.getMapService().changeMap(role, reqTelePort);
    }

    /**
     * 增加银元宝
     */
    public void addSiver(Role role, int siver, Reason reason) {
        if (siver < 0) {
            throw new IllegalArgumentException("增加银元宝不能为负数");
        }
        MessagePusher.pushMessage(role, new RespNotifyMisc("获得" + siver + "银元宝。"));
        int before = role.getSiver();
        role.setSiver(role.getSiver() + siver);
        if (role.getSiver() > 2000000000) {
            role.setSiver(2000000000);
        }
        role.save();

        updateRoleGoldAndSiver(role);


        log.error("addSiver|{}|{}|{}|{}", role.getId(), before, role.getSiver(), reason.getDesc());
    }

    /**
     * 扣除银元宝
     */
    public void subtractSiver(Role role, int siver, Reason reason) {
        if (siver < 0) {
            throw new IllegalArgumentException("扣除银元宝不能为负数");
        }

        int before = role.getSiver();
        if (before < siver) {
            throw new IllegalArgumentException("银元宝不足");
        }
        role.setSiver(role.getSiver() - siver);
        role.save();

        updateRoleGoldAndSiver(role);


        log.error("substractSiver|{}|{}|{}|{}", role.getId(), before, role.getSiver(), reason.getDesc());
    }

    /**
     * 增加首饰精华
     */
    public void addJewelryEssence(Role role, int jewelryEssence) {
        if (jewelryEssence <= 0) {
            return;
        }
        log.error("addJewelryEssence|{}|{}|{}|{}", role.getId(), role.getJewelryEssence(), jewelryEssence);
        role.setJewelryEssence(role.getJewelryEssence() + jewelryEssence);
        updateEssence(role);
    }

    /**
     * 增加首饰精华
     */
    public void subtractJewelryEssence(Role role, int jewelryEssence) {
        if (jewelryEssence <= 0) {
            return;
        }

        role.setJewelryEssence(role.getJewelryEssence() - jewelryEssence);
        updateEssence(role);
    }

    private void updateEssence(Role role) {
        role.save();
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(Collections.singletonList(new FiedValue(450, role.getJewelryEssence())));
        MessagePusher.pushMessage(role, respUpdate);
    }

    /**
     * 增加代金卷
     *
     * @param role
     * @param count
     */
    public void addVoucher(Role role, int count) {
        if (count <= 0) {
            return;
        }

        int roleVoucher = role.getVoucher();
        role.setVoucher(roleVoucher + count);

        RespIconCartoon respIconCartoon = new RespIconCartoon();
        respIconCartoon.setType((short) 3);
        respIconCartoon.setName("代金券");
        respIconCartoon.setParam(String.valueOf(count));
        MessagePusher.pushMessage(role, respIconCartoon);

        SpringUtils.getRoleService().updateRoleMoney(role);
    }

    /**
     * 获得当天在线时长秒数
     */
    public int getOnlineSec(Role role) {
        long now = System.currentTimeMillis();
        if (now > role.getOnlineLoginTime()) {
            int currentOnlineSec = (int) ((now - role.getOnlineLoginTime()) / TimeUtil.ONE_SECOND);
            return currentOnlineSec + role.getPreOnlineSec();
        }

        return 0;
    }

    /**
     * 重置在线时长
     */
    public void resetOnlineSec(Role role) {
        role.setPreOnlineSec(0);
        role.setOnlineLoginTime(System.currentTimeMillis());
    }

    public Role getOnlinePlayer(long uid) {
        if (!DataCache.ONLINE_ROLES.containsKey(uid)) {
            return null;
        }
        return SpringUtils.getPlayerService().getPlayerBy(uid);
    }

    public Role getOnlinePlayer(String name) {
        long uid = SpringUtils.getPlayerService().getUidBy(name);
        return getOnlinePlayer(uid);
    }

    public Role getOnlinePlayer(int roleId) {
        long uid = SpringUtils.getPlayerService().getUidBy(roleId);
        return getOnlinePlayer(uid);
    }

    public Role getPlayerBy(long uid) {
        return SpringUtils.getPlayerService().getPlayerBy(uid);
    }

    public Role getPlayerBy(String name) {
        long uid = SpringUtils.getPlayerService().getUidBy(name);
        return getPlayerBy(uid);
    }

    public Role getPlayerBy(int roleId) {
        long uid = SpringUtils.getPlayerService().getUidBy(roleId);
        return getPlayerBy(uid);
    }

    /**
     * 添加离线提示
     */
    public void addOfflineNotice(Role role, byte noticeType, String notice) {
        if (role == null || StringUtils.isEmpty(notice)) {
            return;
        }

        OfflineNoticeUnit offlineNoticeUnit = new OfflineNoticeUnit(noticeType, notice);
        role.getOfflineNotice().getNotices().add(offlineNoticeUnit);
    }

    /**
     * 弹出离线时的提示
     */
    public void popOfflineNotice(Role role) {
        if (role == null) {
            return;
        }
        if (role.getOfflineNotice() == null || role.getOfflineNotice().getNotices() == null) {
            return;
        }

        for (OfflineNoticeUnit offlineNoticeUnit : role.getOfflineNotice().getNotices()) {
            popOfflineNoticeUnit(role, offlineNoticeUnit);
        }
        role.getOfflineNotice().getNotices().clear();
    }

    private void popOfflineNoticeUnit(Role role, OfflineNoticeUnit offlineNoticeUnit) {
        if (role == null || offlineNoticeUnit == null) {
            return;
        }

        switch (offlineNoticeUnit.getType()) {
            case Const.NOTICE_MSG:
                MessagePusher.pushMessage(role, new RespMsg(offlineNoticeUnit.getContent()));
                break;
            case Const.NOTICE_NOTIFYMISC:
                MessagePusher.pushMessage(role, new RespNotifyMisc(offlineNoticeUnit.getContent()));
                break;
            case Const.NOTICE_NOTIFYMISCEX:
                MessagePusher.pushMessage(role, new RespNotifyMiscEx(offlineNoticeUnit.getContent()));
                break;
        }
    }

    /**
     * 把玩家加入到离线列表
     */
    public void addOffline(Role role) {
        if (role == null) {
            return;
        }
        DataCache.OFFLINE_ROLES.put(role.getUid(), role);
    }

    /**
     * 把玩家从离线列表移除
     */
    public void removeOffline(Role role) {
        if (role == null) {
            return;
        }
        DataCache.OFFLINE_ROLES.remove(role.getUid());
    }

    /**
     * 离线玩家检测
     */
    public void checkOffline() {
        Collection<Role> roles = DataCache.OFFLINE_ROLES.values();
        for (Role role : roles) {
            checkRoleOffline(role);
        }
    }

    private void checkRoleOffline(Role role) {
        if (role == null) {
            return;
        }

        long now = System.currentTimeMillis();
        if (role.getPrevHeartTime() > 0 && now - role.getPrevHeartTime() >= Const.EXPIRE_TIME) {
            if (role.getPos().getMapId() == Const.SHIDAO_MAPID) {
                if (now - role.getPrevHeartTime() >= 3 * 60 * 1000) {
                    EventDispatcher.getInstance().fireEvent(new RoleExpireEvent(EventType.ROLE_EXPIRE, role));
                    SpringUtils.getTeamService().handleRoleExpire(role);
                    removeOffline(role);
                }
            } else {
                EventDispatcher.getInstance().fireEvent(new RoleExpireEvent(EventType.ROLE_EXPIRE, role));
                SpringUtils.getTeamService().handleRoleExpire(role);
                removeOffline(role);
            }
        }
    }

    /**
     * 添加帮贡
     */
    public void addPartyContrib(Role role, int value) {
        SpringUtils.getPartyService().addContrib(role, value);
    }

    /**
     * 消耗帮贡
     */
    public void substractPartyContrib(Role role, int value) {
        SpringUtils.getPartyService().substractContrib(role, value);
    }

    /**
     * 添加帮派活力
     */
    public void addPartyVitality(Role role, int value) {
        SpringUtils.getPartyService().addVitality(role, value);
    }

    /**
     * 添加帮派建设度
     */
    public void addPartyConstruction(Role role, int value) {
        SpringUtils.getPartyService().addConstruction(role, value);
    }

    /**
     * 添加帮派资金
     */
    public void addPartyCapital(Role role, int value) {
        SpringUtils.getPartyService().addCapital(role, value);
    }

    /**
     * 扣除强制PK中的PK值
     */
    public void substractForcePkValue(Role role, int value) {
        if (role.getPkInfoBox().getPkValue() <= 0) {
            return;
        }

        int newValue = role.getPkInfoBox().getPkValue() - value;
        if (newValue < 0) {
            newValue = 0;
        }

        role.getPkInfoBox().setPkValue(newValue);
        role.save();

        /** 产生一个pk值改变事件 */
        EventDispatcher.getInstance().fireEvent(new PkValueChangeEvent(EventType.PK_VALUE_CHANGE, role, newValue));
    }

    /**
     * 增加充值积分
     */
    public void addRechargeScore(Role role, int score) {
        if (score < 0) {
            throw new IllegalArgumentException("增加充值积分不能为负数");
        }
        int newScore = role.getActivity().getRechargeScore() + score;
        if (newScore > Const.MAX_RECHARGE_SCORE) {
            newScore = Const.MAX_RECHARGE_SCORE;
        }

        /**充值积分*/
        int before = role.getActivity().getRechargeScore();
        role.getActivity().setRechargeScore(newScore);
        role.save();
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("获得#R" + score + "#n积分"));
        log.info("addRechargeScore|{}|{}|{}|{}", role.getUid(), before, score, role.getActivity().getRechargeScore());
        /*
         * 判断是否存在积分任务。如果存在，修改数值，如果不存在创建任务
         */
        this.scoreTask(role,newScore);
    }

    /**
     * 创建积分任务
     * @param role
     * @param score
     */
    public void scoreTask(Role role,int score){
        NewTaskService taskService = SpringUtils.getTaskService();
        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.RECHARGE_SCORE_TASKID, role);

        if (taskSet == null) {
            taskSet=new TaskSet();
            taskSet.setId(999);
            taskSet.setButtton("我的积分000");
            taskSet.setTaskName("积分系统");
            taskSet.setNpcName("fjdfkj");
            taskSet.setTaskJieshao("#Y剩余积分："+score);
            taskSet.setTaskGift("无");
            taskSet.setTaskZhiyin("#Y剩余积分："+score);
            // taskSet.setTaskZhiyin("剩余积分："-newScore);
        }
//
        RechargeScoreTaskHandler handler=(RechargeScoreTaskHandler)TaskHelper.INSTANCE.getTaskHandler(TaskType.SCORE);
        handler.acceptTask(role,taskSet);
    }  /**
     * 创建称号任务
     * @param role
     * @param score
     */
    public void titleTask(Role role){
        NewTaskService taskService = SpringUtils.getTaskService();
        TaskSet taskSet = taskService.getTaskSet(9998, role);
        LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
        int polor = 0 ;
        int attr = 0 ;
        for (Map.Entry<String, TitleInfo> stringTitleInfoEntry : hashMap.entrySet()) {
            TitleDetailInfo titleDetailInfo = null;
            if("试道大会".equals(stringTitleInfoEntry.getKey())){
                titleDetailInfo= TitleInfoService.allMapByGroup.get(stringTitleInfoEntry.getValue().getTitle());
            }else{
                titleDetailInfo= TitleInfoService.allMapByGroup.get(stringTitleInfoEntry.getKey());
            }

            if(titleDetailInfo == null){
                continue;
            }
            if( StringUtils.isEmpty(titleDetailInfo.getAttr())){
                continue;
            }
            JSONArray titleJars = JSONObject.parseArray(titleDetailInfo.getAttr());
            for (Object titleJar : titleJars) {
                JSONObject jsonObject =(JSONObject)titleJar;
                String field = jsonObject.getString("field");
                int num = jsonObject.getIntValue("value");
                if("所有相性".equals(field)){
                    polor += num;
                }
                if("所有属性".equals(field)){
                    attr += num;
                }
            }
        }
        if (taskSet == null) {
            taskSet=new TaskSet();
            taskSet.setId(9998);
            taskSet.setButtton("我的任务000");
            taskSet.setTaskName("称号系统");
            taskSet.setNpcName("fjdfkjch");
            String msg = "#Y所有相性："+polor+"\n所有属性："+attr;
            taskSet.setTaskJieshao(msg);
            taskSet.setTaskGift("无");
            taskSet.setTaskZhiyin(msg);
            // taskSet.setTaskZhiyin("剩余积分："-newScore);
        }
//
        RechargeScoreTaskHandler handler=(RechargeScoreTaskHandler)TaskHelper.INSTANCE.getTaskHandler(TaskType.SCORE);
        handler.acceptTask(role,taskSet);
    }

    /**
     * 创建每日累计充值赠送相性任务
     * @param role
     */
    public void mrljAddPolorTask(Role role){
        NewTaskService taskService = SpringUtils.getTaskService();
        String yyyyMMdd = DateUtils.formatDate(new Date(), "yyyyMMdd");
        TaskSet taskSet = taskService.getTaskSet(9997, role);
        int polor  = role.getExtendBox().getPolorNum();
        int mrlj = redisService.getInt("mrlj_" + yyyyMMdd + role.getId());
        if (taskSet == null) {
            taskSet=new TaskSet();
            taskSet.setId(9997);
            taskSet.setButtton("我的任务000");
            taskSet.setTaskName("每日累计充值系统");
            taskSet.setNpcName("fjdfkjch");
            String msg = "#Y今日充值："+mrlj+"\n各阶段奖励点开任务查看";
            taskSet.setTaskJieshao(msg);

            String mgs = DataCache.REDIS_DATA.get("mrlj_task_reward_content");

            taskSet.setTaskGift(mgs);
            taskSet.setTaskZhiyin(msg);
            // taskSet.setTaskZhiyin("剩余积分："-newScore);
        }
//
        RechargeScoreTaskHandler handler=(RechargeScoreTaskHandler)TaskHelper.INSTANCE.getTaskHandler(TaskType.SCORE);
        handler.acceptTask(role,taskSet);
    }

    /**
     * 创建转生增加属性任务
     * @param role
     */
    public void zhuanshengAddPolorTask(Role role){
        NewTaskService taskService = SpringUtils.getTaskService();

        TaskSet taskSet = taskService.getTaskSet(9996, role);
        int polor  = role.getExtendBox().getZhuanshengpolor();
        int attr  =  role.getExtendBox().getZhuanshengAttr();
        int zhuansheng = role.getExtendBox().getZhuansheng();
        if (taskSet == null) {
            taskSet=new TaskSet();
            taskSet.setId(9997);
            taskSet.setButtton("我的任务000");
            taskSet.setTaskName("转生系统");
            taskSet.setNpcName("zszjsx");
            String msg = "#Y转生次数："+zhuansheng+"#n \n#Y所相加成："+polor +"#n \n#Y所属加成："+attr+"#n";
            taskSet.setTaskJieshao(msg);
            taskSet.setTaskGift("转生说明请到#Y转生使者#n处查看");
            taskSet.setTaskZhiyin(msg);
            // taskSet.setTaskZhiyin("剩余积分："-newScore);
        }
//
        RechargeScoreTaskHandler handler=(RechargeScoreTaskHandler)TaskHelper.INSTANCE.getTaskHandler(TaskType.SCORE);
        handler.acceptTask(role,taskSet);
    }

    /**
     * 创建萝卜桃子任务
     */
    public void luobotaozirenwu(Role role) {
        if (role.getActivity().isLuobotaozi()) {
            NewTaskService taskService = SpringUtils.getTaskService();
            TaskSet taskSet = taskService.getTaskSet(2226, role);
            if (taskSet == null) {
                taskSet = new TaskSet();
                taskSet.setId(2226);
                taskSet.setButtton("萝卜桃子#Y任务");
                taskSet.setTaskName("萝卜桃子");
                taskSet.setNpcName("fjdfkj4");
                taskSet.setTaskJieshao("萝卜桃子活动开启时间会公告谣言通知。\n前往桃柳林或官道北击杀萝卜桃子的<强盗>\n击杀完毕有百分之80几率获得萝卜、桃子、大桃子\n活动结束以后、可以前往千面怪提交萝卜桃子！");
                taskSet.setTaskGift("#R1个    萝卜奖励道行200天！\n#R1个    桃子奖励道行200天！\n#R1个大桃子奖励道行2年！");
                taskSet.setTaskZhiyin("萝卜桃子#Y任务");
            }

            LuobotaoziTaskHandler handler = (LuobotaoziTaskHandler)TaskHelper.INSTANCE.getTaskHandler(TaskType.luobotaozi);
            handler.acceptTask(role, taskSet);
        }
    }

    public void scoreRank(Role role,int rank){
        NewTaskService taskService = SpringUtils.getTaskService();
        TaskSet taskSet = taskService.getTaskSet(9999, role);

        if (taskSet == null) {
            taskSet=new TaskSet();
            taskSet.setId(9999);
            taskSet.setButtton("我的排名");
            taskSet.setTaskName("排名<战力>");
            taskSet.setNpcName("zlpm");
            taskSet.setTaskJieshao("#Y当前排名："+rank);
            taskSet.setTaskGift("无");
            taskSet.setTaskZhiyin("#Y当前排名："+rank);
            // taskSet.setTaskZhiyin("剩余积分："-newScore);
        }
//
        RechargeScoreTaskHandler handler=(RechargeScoreTaskHandler)TaskHelper.INSTANCE.getTaskHandler(TaskType.SCORE);
        handler.acceptTask(role,taskSet);
    }

    /**
     * 减少充值积分
     */
    public void substractChargeScore(Role role, int score) {
        if (score < 0) {
            throw new IllegalArgumentException("扣除充值积分不能为负数");
        }
        int before = role.getActivity().getRechargeScore();
        if (before < score) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("积分不足，扣除#R" + score + "积分#n失败！！"));
            throw new IllegalArgumentException("充值积分不足");
        }

        role.getActivity().setRechargeScore((before - score));
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("扣除#R" + score + "积分#n成功！！"));
        role.save();

        log.error("substractChargeScore|{}|{}|{}|{}", role.getUid(), before, score, role.getActivity().getRechargeScore());
        this.scoreTask(role, role.getActivity().getRechargeScore());
    }

    public boolean isOpenSet(Role role, String key) {
        return role.getExtendBox().getSetMap().getOrDefault(key, 0) == 1;
    }

    /**
     * 切换元婴状态
     */
    public void changeChildState(Role role, byte state) {

        ChildInfo childInfo = role.getChildInfo();

        /**如果没有元婴就返回*/
        if (childInfo.getType() <= 0) {
            return;
        }
        /**如果要切换的状态不对 返回*/
        if (state > 2 || state < 0) {
            return;
        }
        /**如果当前的状态跟要切换的状态一致 返回*/
        if (childInfo.getState() == state) {
            return;
        }
        childInfo.setState(state);

        role.save();

        sendExtraAttribute(role);

        /**更新外观包 广播*/
        broadcastService.sendUpdateAppear(role);
    }

    /**
     * * 获得元婴
     * * 类型
     * 元婴的类型  切换状态的时候 1 3 都发1  2和4都发 2
     * NO_CHILD = 0,               -- 无
     * YUANYING = 1,               -- 元婴
     * XUEYING  = 2,               -- 血婴
     * UPGRADE_IMMORTAL    = 3,    -- 仙
     * UPGRADE_MAGIC       = 4,    -- 魔
     */
    public void getChild(Role role, byte type) {
        /**因为默认有一个对象 所以直接取出来 设置类型就好了*/
        ChildInfo childInfo = role.getChildInfo();
        childInfo.setType(type);
        role.save();
        sendExtraAttribute(role);
    }

    public Role getOnlinePlayerFromDB(String name) {
        Role role = dao.fetch(Role.class, Cnd.where("name", "=", name));
        if (role != null) {
            role.doAfterInit();
        }
        return role;
    }

    public boolean canLogin(String sid, IoSession session) {
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        AccountService accountService = SpringUtils.getBean(AccountService.class);
        {
            AccountLogin accountLogin = accountService.queryAccount(sid);
            if (accountLogin == null) {
                MessagePusher.pushMessage(session, new RespNotifyMiscEx("账号不存在！！"));
                serverService.getScheduledExecutorService().schedule(new Runnable() {
                    @Override
                    public void run() {
                        session.closeNow();
                    }
                }, 3, TimeUnit.SECONDS);
                return false;
            }
            if (accountLogin.getIsStop() == 1) {
                MessagePusher.pushMessage(session, new RespNotifyMiscEx("账号已经被封闭，请联系管理员！！"));
                serverService.getScheduledExecutorService().schedule(new Runnable() {
                    @Override
                    public void run() {
                        session.closeNow();
                    }
                }, 3, TimeUnit.SECONDS);
                return false;
            }
        }
        return true;
    }

    public void invite(Role role, String username) {
        AccountService accountService = SpringUtils.getBean(AccountService.class);
        AccountLogin self = accountService.queryAccount(role.getSid());
        if (self == null) {
            return;
        }
        if (username.equals(self.getUsername())) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("不能填写#R自己"));
            return;
        }
        AccountLogin accountLogin = accountService.queryByUsername(username);
        if (accountLogin == null) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("邀请人不存在"));
            return;
        }
        // yyyy-MM-dd
        Date date = TimeUtil.parse("2020-09-14");
        if (date.after(self.getCreateTime())) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("当前账号为#R9月14日#n以前创建的账号，不能填写邀请人"));
            return;
        }
        Invite invite = accountService.fetchInvite(self.getUsername());
        if (invite != null) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("不能重复填写邀请人，当前邀请人#R" + invite.getInviteAccount()));
            return;
        }
        int count = accountService.countInvite(username);
        if (count >= 50) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("邀请人的账号已经达到上限，无法获得更多邀请奖励。"));
            return;
        }
        String today = TimeUtil.formatDate(new Date(), "yyyy-MM-dd");
        int dayCount = accountService.countInvite(username, today + " 00:00:00", today + " 23:59:59");
        if (dayCount >= 5) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("今日邀请已经达到上限，请明天再试"));
            return;
        }
        // 每天只能填五个
        invite = new Invite();
        invite.setInviteAccount(username);
        invite.setAccount(self.getUsername());
        invite.setRmb(0);
        invite.setCreatetime(new Date());
        invite.setUpdatetime(new Date());
        invite.setState(1);
        accountService.insertInvite(invite);
        {
            invite = new Invite();
            invite.setInviteAccount(username);
            invite.setAccount(self.getUsername());
            invite.setRmb(200);
            invite.setCreatetime(new Date());
            invite.setUpdatetime(new Date());
            invite.setState(0);
            accountService.insertInvite(invite);
        }
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("填写邀请人成功！"));
    }

    public void offlineReward(Role role) {
        long round = role.getOfflineNotice().getRound();
        int lastRound = getLastRound(role);
        int costround = (int) (round - lastRound);
        NutMap nutMap = null;
        RoleOfflineNotice offlineNotice = role.getOfflineNotice();
        if (offlineNotice.getActivityType() != null) {
            if (role.getOfflineNotice().getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_XIANGYAO_TASK.getActivityId())) {
                nutMap = role.getOfflineNotice().getNutMapXiangyao();
            } else if (role.getOfflineNotice().getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FUMO_TASK.getActivityId())) {
                nutMap = role.getOfflineNotice().getNutMapFumo();
            } else if (role.getOfflineNotice().getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK.getActivityId())) {
                nutMap = role.getOfflineNotice().getNutMapFeixian();
            }else if (role.getOfflineNotice().getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_XIANGYAO_TASK2.getActivityId())) {
                nutMap = role.getOfflineNotice().getNutMapXiangyao();
            }else if (role.getOfflineNotice().getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FUMO_TASK2.getActivityId())) {
                nutMap = role.getOfflineNotice().getNutMapFumo();
            }else if (role.getOfflineNotice().getActivityType().getActivityId().equals(ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK2.getActivityId())) {
                nutMap = role.getOfflineNotice().getNutMapFeixian();
            }
        }
        final ShuaDaoTaskHandler bean = SpringUtils.getBean(ShuaDaoTaskHandler.class);
        SpringUtils.getBean(ShuaDaoTaskHandler.class).add(nutMap.getInt("daohang", 0) * costround
                , nutMap.getInt("qianneng", 0) * costround
                , nutMap.getInt("money", 0) * costround
                , nutMap.getInt("petWuxue", 0) * costround
                , nutMap.getInt("size", 0) * costround
                , role, costround);
        role.getOfflineNotice().setLeijiTime(0);
        role.getOfflineNotice().setRound(lastRound);
        int ten = SpringUtils.getBean(ShuaDaoTaskHandler.class).getTenShuaDaoUsedTime(role, role.getOfflineNotice().getActivityType());
        ten = ten / 10;
        int lasttime = role.getOfflineNotice().getOfflineTime() - costround * ten;

        role.getOfflineNotice().setOfflineTime(lasttime <= 0 ? 0 : lasttime);
        role.save();
        sendShuadaoStauts(role);
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("领取离线刷道奖励成功"));
    }

    public void enterMap(IoSession session, Role role) throws Exception {
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        List<PlayerProfile> playerProfiles = SpringUtils.getPlayerService().getPlayersBy(role.getSid());
        for (PlayerProfile playerProfile : playerProfiles) {
            /**这里是为了让顶号的时候上之前在线的那个角色 不上选定的角色*/
            Role onlineRole = roleService.getOnlinePlayer(playerProfile.getGid());
            if (onlineRole != null) {
                onlineRole.save();
                Thread.sleep(1000);
                IoSession ioSession = SessionUtils.getSessionBy(onlineRole.getUid());
                if (ioSession != null && ioSession.getId() != session.getId()) {
                    RespOtherLogin respOtherLogin = new RespOtherLogin();
                    respOtherLogin.setResult((short) 1);
                    MessagePusher.pushMessage(ioSession, respOtherLogin);
                    Thread.sleep(1000);
                    ioSession.write(new RespKickClient("你的账号已在其它设备登录。")).addListener(new IoFutureListener<IoFuture>() {
                        @Override
                        public void operationComplete(IoFuture future) {
                            log.error("角色:[{}]顶号退出游戏,SessionId:[{}]", onlineRole.getUid(), session.getId());
                            ioSession.closeNow();
                        }
                    });
                }
            }
        }
        Account account = SpringUtils.getAccountService().getAccount(role.getSid());
        if (serverService.getServer().getId() == 10000 && account.getPrivilege() < 200) {
            if (!SpringUtils.getBean(ShiDaoHandler.class).enterKuafu()) {
                MessagePusher.pushMessage(session, new RespNotifyMiscEx("跨服试道已经结束，不能进入跨服专线。"));
                return;
            }
        }
//        log.error("角色:[{}]进入游戏,Id:[{}],SessionId:[{}]", role.getName(), role.getId(), session.getId());
        // 缓存当前登录角色信息
        SessionManager.INSTANCE.registerSession(role.getRoleId(), session);
        /**添加到在线列表*/
        roleService.addOnline(role);
        /**从离线列表删除*/
        roleService.removeOffline(role);

        session.setAttribute(SessionProperties.CLIENT_STATUS, Const.CLIENT_ACTIVE);
        session.setAttribute(SessionProperties.PLAYER_ID, role.getRoleId());
        session.setAttribute(SessionProperties.PLAYER_UID, role.getUid());
        session.setAttribute(SessionProperties.PLAYER, role);
        session.setAttribute(SessionProperties.PLAYER_NAME, role.getName());
        // 绑定线程id
        role.setDistributeKey(SessionManager.INSTANCE.getNextDistributeKey());
        int currTime = Math.toIntExact(System.currentTimeMillis() / 1000);

        /**登录的时候结束对话*/
        role.getTalk().endTalk();

        ServerService serverService = SpringUtils.getBean(ServerService.class);
        RespRoleAlreadyLogin respRoleAlreadyLogin = new RespRoleAlreadyLogin();
        respRoleAlreadyLogin.setRoleName(role.getName());
        MessagePusher.pushMessage(role, respRoleAlreadyLogin);

        RespCS_ServerType respCSServerType = new RespCS_ServerType(); //非安全区域提示
        if (SpringUtils.getBean(CrossServerConfig.class).isCenterServer()) {
            respCSServerType.setServer_type(role.getCrossInfo().getCrossType());
        }
        MessagePusher.pushMessage(role, respCSServerType);

        //发送消息
        SchedulerManager.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                RespReplyServerTime respReplyServerTime = new RespReplyServerTime();
                respReplyServerTime.setServer_time(currTime);
                String ipAddr = session.getRemoteAddress().toString().split(":")[0].replace("/", "");
                respReplyServerTime.setIp(ipAddr);
                MessagePusher.pushMessage(role, respReplyServerTime);
            }
        }, 8000);//对其服务器时间 延迟10秒
        if (role.getLockTime() > System.currentTimeMillis()) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date = new Date(role.getLockTime());
            String tips = simpleDateFormat.format(date);

            RespOtherLogin respOtherLogin = new RespOtherLogin();
            respOtherLogin.setContent("当前角色被封闭至#R" + tips + "#n。");
            respOtherLogin.setResult((short) 2);
            MessagePusher.pushMessage(role, respOtherLogin);
            return;
        }
        if (role.getBlockEndTime() > 0 && System.currentTimeMillis() < role.getBlockEndTime()) {
            RespOtherLogin respOtherLogin = new RespOtherLogin();
            String msg = MessageFormat.format("#Y{0}#n之后方可正常登录。", TimeUtil.formatDate(new Date(role.getBlockEndTime()), TimeUtil.DEFAULT_DATE_FORMAT));
            respOtherLogin.setContent(msg);
            respOtherLogin.setResult((short) 2);
            MessagePusher.pushMessage(role, respOtherLogin);
            log.info("{}({}){}", role.getUid(), role.getName(), msg);
            return;
        }

        Pos position = role.getPos();
//
//        //加载登录计次
        RespLoginCount respLoginCount = new RespLoginCount();
        respLoginCount.setName(role.getName());
        role.setLogins(role.getLogins() + 1);
        respLoginCount.setMsg(role.getName() + "是第 " + 25 + " 次登录");
        respLoginCount.setGid(role.getGid());
        MessagePusher.pushMessage(role, respLoginCount);

        sendPacket(role);

        Message message = SpringUtils.getBean(SafeService.class).getLockStatus(role); //密码锁状态
        MessagePusher.pushMessage(role, message);

        SpringUtils.getBean(WelfareService.class).openWelfare(session, new ReqGeneralNotify());


        // 发送面板信息

        List<FiedValue> list = FieldUtils.mapInfo(role,position.getMapId());
        RespUpdate respUpdate = new RespUpdate();

        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(list);

        MessagePusher.pushMessage(role, respUpdate);


        MessagePusher.pushMessage(role, new RespUpdateAntiaddictionStatus());//防沉迷  实名



        // 上线加载装备
        RespFlushPack respFlushPack = new RespFlushPack();
        respFlushPack.setType("bag");
        MessagePusher.pushMessage(role, respFlushPack);


        /**产生一个进入地图事件*/
        EventDispatcher.getInstance().fireEvent(new EnterMapEvent(EventType.ENTER_MAP, role,0));

        /**产生一个登录事件*/

        EventDispatcher.getInstance().fireEvent(new LoginEvent(EventType.LOGIN, role));

        /**
         * 进入地图需要判断内存中有没有队伍
         */

        TeamService teamService = SpringUtils.getBean(TeamService.class);
        Team team = teamService.getTeam(role.getRoleId());
        if (team != null) {
            //队伍成员没有时，则删除与对应的team的映射关系
            int teamCount = teamService.getTeamCount(team);
            if (teamCount == 0) {
                SessionCache.ROLE_TEAM.remove(role.getRoleId());
            } else {
                teamService.updateTeamList(role);
                teamService.updateTeamListEX(team);
            }
        }


        FieldUtils.sendChangeIcon(role);

        // 返回线路信息
        Server server = serverService.getServer();
        RespLineInfo respLineInfo = new RespLineInfo();
        respLineInfo.setDistName(server.getName());
        respLineInfo.setLineName(server.getSonName());
        respLineInfo.setTime(currTime);
        MessagePusher.pushMessage(role, respLineInfo);

        // 返回设置数据
        List<SettingInfo> lists = new ArrayList<>();
        role.getExtendBox().getSetMap().forEach((key, setting) -> {
            SettingInfo settingInfo = new SettingInfo();
            settingInfo.setSettingName(key);
            settingInfo.setSettingVaule(Short.parseShort(setting.toString()));
            if (key.equals("sight_scope")) {
                settingInfo.setSettingVaule((short) 0);
            }
            lists.add(settingInfo);
        });



        RespSettingInfo respSettingInfo = new RespSettingInfo();
        respSettingInfo.setList(lists);
        MessagePusher.pushMessage(role, respSettingInfo);

        //清除组队的申请列表和邀请列表
        RespRequestList respRequestList = new RespRequestList();
        respRequestList.setAsk_type("invite_join");
        MessagePusher.pushMessage(role, respRequestList);

        respRequestList.setAsk_type("request_join");
        MessagePusher.pushMessage(role, respRequestList);

        /**福利*/
        RespOpenWelfare respOpenWelfare = SpringUtils.getBean(WelfareService.class).getRespOpenWelfare(role);
        MessagePusher.pushMessage(role, respOpenWelfare);
        /**
         * 上线加载会员状态
         */

        RespVipStatus RespVipStatus = new RespVipStatus(); //会员状态
        if (role.isVip()) {
            RespVipStatus.setType(role.getVipType());
            RespVipStatus.setExpireTime(role.getExpireTime());
            RespVipStatus.setReceive(role.isReceive());
        }
        MessagePusher.pushMessage(role, RespVipStatus);

        RespGoldStallAuctionBidGids respGoldStallAuctionBidGids = new RespGoldStallAuctionBidGids();
        MessagePusher.pushMessage(role, respGoldStallAuctionBidGids);

        RespTradingRole respTradingRole = new RespTradingRole();
        MessagePusher.pushMessage(role, respTradingRole);

        MessagePusher.pushMessage(role, respOpenWelfare);
        MessagePusher.pushMessage(role, RespVipStatus);

        {
            RespActiviyDataList respActiviyDataList = new RespActiviyDataList();
            respActiviyDataList.setActivityList(new ArrayList<>());
            Activity activity = new Activity();
            activity.setKey("newdisthelp");
            respActiviyDataList.getActivityList().add(activity);
            activity = new Activity();
            activity.setKey("realname_gift");
            respActiviyDataList.getActivityList().add(activity);
            MessagePusher.pushMessage(role, respActiviyDataList);
        }
        {
            RespWeizhi33 respWeizhi33 = new RespWeizhi33();
            respWeizhi33.setTips(new ArrayList<>());
            Activity activity = new Activity();
            activity.setKey("57EC59841CE066013400");
            respWeizhi33.getTips().add(activity);
            activity = new Activity();
            activity.setKey("5BACE4D20AF53B0134F9");
            respWeizhi33.getTips().add(activity);
            MessagePusher.pushMessage(role, respWeizhi33);
        }

        RespMyAppenticeInfo respMyAppenticeInfo = new RespMyAppenticeInfo();
        MessagePusher.pushMessage(role, respMyAppenticeInfo);
        RespWeizhi35 RespWeizhi35 = new RespWeizhi35();
        MessagePusher.pushMessage(role, RespWeizhi35);
        MessagePusher.pushMessage(role, RespWeizhi35);

        respSettingInfo = new RespSettingInfo();
        ArrayList<SettingInfo> settingList = new ArrayList<>();
        {
            SettingInfo settingInfo = new SettingInfo();
            settingInfo.setSettingVaule((short) 0);
            settingInfo.setSettingName("total_switch");
            settingList.add(settingInfo);
        }
        respSettingInfo.setList(settingList);
        MessagePusher.pushMessage(role, respSettingInfo);

        RespTotalSwitch respTotalSwitch = new RespTotalSwitch();
        MessagePusher.pushMessage(role, respTotalSwitch);

        {
            /**
             * 发送角色称谓
             */


            List<TitleInfo> titleInfos = new ArrayList<>();
            LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
            for (Map.Entry<String, TitleInfo> entry : hashMap.entrySet()) {
                titleInfos.add(entry.getValue());
            }
            RespTitleList respTitleList = new RespTitleList();
            respTitleList.setList(titleInfos);
            MessagePusher.pushMessage(role, respTitleList);

        }


        RespCommunityAddress respCommunityAddress = new RespCommunityAddress();
        respCommunityAddress.setAddr("http://vwd.leiting.com/#/index");
        MessagePusher.pushMessage(role, respCommunityAddress);


        /**
         * //上线提示
         */


        RespNotifyMisc respNotifyMisc = new RespNotifyMisc();
        respNotifyMisc.setMsg("你在#R" + server.getSonName() + "#n上线啦！");
        respNotifyMisc.setTime(currTime);
        MessagePusher.pushMessage(role, respNotifyMisc);

        Thread.sleep(1000);//Todo 不知道为什么 这个延迟不加的话 角色头像有问题

        //上线提示
        SendPopMessage respGeneralNotify2 = new SendPopMessage();
        String onlineMessage = "Mingrzbgz2021ZQZDRuleDlg|"+DataCache.REDIS_DATA.get("onlineMessage");
        respGeneralNotify2.setName(onlineMessage);
        respGeneralNotify2.setType((byte)2);
        MessagePusher.pushMessage(role, respGeneralNotify2);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lastTime = role.getEnterTime() * 1000L;
        if (role.getEnterTime() <= 0) {
            lastTime = System.currentTimeMillis();
        }
        Date lastDate = new Date(lastTime);
        MessagePusher.pushMessage(role, new RespNotifyMisc("你上次登录的时间为#Y" + simpleDateFormat.format(lastDate) + "#n。#R注意：如有疑问，请尽快设定安全码验证或更改密码，以免造成不必要的损失。#n"));

        role.setEnterTime(currTime);

        /**设置*/


        role.setOnlineLoginTime(System.currentTimeMillis());
        // 更改状态为在线
        role.setOn_line(1);
        role.setPrevHeartTime(0);
        if (role.getOfflineNotice().getOfflineTime() > 1500 * 60 + 90 * 60) {
            role.getOfflineNotice().setOfflineTime(1500 * 60 + 90 * 60);
        }
        role.save();

        SessionManager.INSTANCE.removeFromAnonymous(session);

        RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_YOUNG_PERSON_LIMIT);//通知未成年人操作限制
        respGeneralNotify.setValue("1");
        MessagePusher.pushMessage(role, respGeneralNotify);

        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_IOS_REVIEW);//// IOS评审信息
        respGeneralNotify.setValue("1");
        MessagePusher.pushMessage(role, respGeneralNotify);
        //注释了绿标显示
        //听说 说是有bug  开放起来试试
        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_SEND_INIT_DATA_DONE);//服务器通知客户端角色数据发送完成
        respGeneralNotify.setValue("1");
        MessagePusher.pushMessage(role, respGeneralNotify);


        SpringUtils.getBean(TuoguanController.class).dakaituoguan(session,null);

        //试着发送一下lua脚本试试
        Resexelua resexelua = new Resexelua();
        String map_s = "" ;
        map_s = "function GameMgr:MSG_CHECK_SERVER(data)  end";
        resexelua.setMsg(map_s);
        MessagePusher.pushMessage(role, resexelua);

        Resexelua resexelua2= new Resexelua();
        String map_t = "local data = {} data.gids={gids="+role.getGid()+"} TeamMgr:MSG_TEAM_ASSESS_LIST(data)";
        resexelua2.setMsg(map_t);
        MessagePusher.pushMessage(role, resexelua2);


        Resexelua resexelua3= new Resexelua();
        String map_d = "function GameMgr:checkServer()  end";
        resexelua3.setMsg(map_d);
        MessagePusher.pushMessage(role, resexelua3);
//
//        Resexelua resexelua4= new Resexelua();
//        String map_e = "function MsgParser:MSG_RECHARGE_SCORE_GOODS_LIST(pkt, data) data.startTime = pkt:GetLong() data.endTime = pkt:GetLong() data.deadline = pkt:GetLong() data.ownPoint = pkt:GetShort() data.totalPoint = pkt:GetLong() data.count = pkt:GetChar() for i = 1, data.count do local item = {} item.no = pkt:GetChar() + 1 item.rewardStr = pkt:GetLenString() item.point = pkt:GetShort() item.num = pkt:GetShort() data[item.no] = item end end";
//        resexelua4.setMsg(map_e);
//        MessagePusher.pushMessage(role, resexelua4);

        SpringUtils.getBean(JiehunController.class).openDanmu(role);

        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_MAIL_ALL_LOADED);// 通知客户端加载所有邮件完毕
        respGeneralNotify.setValue("1");
        MessagePusher.pushMessage(role, respGeneralNotify);
        this.luobotaozirenwu(role);
        respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        ArrayList<FiedValue> values = new ArrayList<>();
        {
            values.add(new FiedValue(301, 3, 0));
            values.add(new FiedValue(302, 1, 0));
            values.add(new FiedValue(303, 4, ""));
            values.add(new FiedValue(90, 4, ""));
            values.add(new FiedValue(304, 4, ""));
            values.add(new FiedValue(305, 4, role.getGid()));

        }
        respUpdate.setList(values);
        MessagePusher.pushMessage(role, respUpdate);

        respGeneralNotify = new RespGeneralNotify();
        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_EXORCISM_STATUS);//驱魔香状态
        if (role.isAvoidMonster()) {
            respGeneralNotify.setValue("1");
        } else {
            respGeneralNotify.setValue("0");
        }
        MessagePusher.pushMessage(role, respGeneralNotify);



        /**
         * 发送角色称谓
         */


        List<TitleInfo> titleInfos = new ArrayList<>();
        LinkedHashMap<String, TitleInfo> hashMap = role.getExtendBox().getTitleList();
        for (Map.Entry<String, TitleInfo> entry : hashMap.entrySet()) {
            titleInfos.add(entry.getValue());
        }
        //log.error("我走到le刷新面板aa我走到le刷新面板aa我走到le刷新面板aa我走到le刷新面板aa我走到le刷新面板aa");
        roleService.refreshRole(role);


        RespTitleList respTitleList = new RespTitleList();
        respTitleList.setList(titleInfos);
        MessagePusher.pushMessage(role, respTitleList);

        roleService.sendYinDe(role);
        roleService.sendUpdatePeiYuanStage(role);
        MessagePusher.pushMessage(role, new RespChatUseCard());







        SpringUtils.getFightService().handleLoginEvent(new LoginEvent(EventType.LOGIN, role));



//        SpringUtils.getBean(ChargeActivityService.class).sendReward();
//        PayNotifyInfo payNotifyInfo = new PayNotifyInfo();
//        payNotifyInfo.setMoney(6000);
//        payNotifyInfo.setTradeNo("55555555");
//        payNotifyInfo.setAccount("4f9a40AM");
//        payNotifyInfo.setRoleUid(role.getUid());
//        SpringUtils.getBean(OrderService.class).handleOrder(payNotifyInfo);
//        serverService.getScheduledExecutorService().schedule(new Runnable() {
//            @Override
//            public void run() {
//                SpringUtils.getBean(ShiDaoHandler.class).send(role, (byte) 1,System.currentTimeMillis()+"",68+"");
//                SpringUtils.getBean(ShiDaoHandler.class).send(role, (byte) 2,System.currentTimeMillis()+"",68+"");
//                SpringUtils.getBean(ShiDaoHandler.class).send(role, (byte) 3,System.currentTimeMillis()+"",68+"");
//            }
//        },20, TimeUnit.SECONDS);

        role.popTempCache("dig_treasure_end_time");
    }

    private void sendPacket(Role role) {
        RespWeizhi respWeizhi = new RespWeizhi();
        MessagePusher.pushMessage(role, respWeizhi);

        Resexelua resexelua = new Resexelua();
        String msg = " local data = {} data.is_open=1 data.is_ghost_pet_open=1 data.is_srdf_complete=1 GameMgr:MSG_GHOSTDOM_INFO(data)";
        resexelua.setMsg(msg);
        MessagePusher.pushMessage(role, resexelua);

        RespRealNameAuth respRealNameAuth = new RespRealNameAuth();
        respRealNameAuth.setNameAuth(true);
        respRealNameAuth.setPhoneAuth(true);
        respRealNameAuth.setName("****");
        respRealNameAuth.setPhone("***********");
        respRealNameAuth.setIdCard("621322199909090909");
        MessagePusher.pushMessage(role, respRealNameAuth);

        int currTime = new Long(System.currentTimeMillis() / 1000).intValue();

        RespSuijiRichangeFanbei respSuijiRichangeFanbei = new RespSuijiRichangeFanbei();
        List<String> para = new ArrayList<>();
        para.add("tongtt");
        respSuijiRichangeFanbei.setPara(para);
        MessagePusher.pushMessage(role, respSuijiRichangeFanbei);
        RespCS_ServerType respCSServerType = new RespCS_ServerType(); //非安全区域提示
        if (SpringUtils.getBean(CrossServerConfig.class).isCenterServer()) {
            respCSServerType.setServer_type(role.getCrossInfo().getCrossType());
        }
        MessagePusher.pushMessage(role, respCSServerType);

        RespNewPartyWar respNewPartyWar = new RespNewPartyWar();
        respNewPartyWar.setTime(currTime - 100000);
        MessagePusher.pushMessage(role, respNewPartyWar);

        RespGoldStallConfig respGoldStallConfig = new RespGoldStallConfig();//屏蔽珍宝
        respGoldStallConfig.setIs_enable((byte) 1);  //整个珍宝系统是否可用
        respGoldStallConfig.setEnable_gold_stall_cash((byte) 1);  //珍宝系统是否可以进行金钱交易 (是否有金钱标签)    //1是只有金钱的标签   2是全部标签
        respGoldStallConfig.setSell_cash_aft_days((byte) 7); //珍宝金钱交易在开服几天后开放
        respGoldStallConfig.setEnable_appoint((byte) 1);//珍宝金钱交易是否已经开放过
        respGoldStallConfig.setEnable_autcion((byte) 1);//珍宝金钱交易是否开放指定交易
        respGoldStallConfig.setStart_gold_stall_cash((byte) 1);  //是否可以进行拍卖
        MessagePusher.pushMessage(role, respGoldStallConfig);

        RespNotifyChushiLevel respNotifyChushiLevel = new RespNotifyChushiLevel();
        respNotifyChushiLevel.setChushiLevel((byte) 115);//平台默认72
        MessagePusher.pushMessage(role, respNotifyChushiLevel);

        RespaddVerifyInfo respaddVerifyInfo = new RespaddVerifyInfo(); //商城红点 提示?
        respaddVerifyInfo.setTime(currTime);
        respaddVerifyInfo.setTime1(currTime);
        MessagePusher.pushMessage(role, respaddVerifyInfo);

        RespEnableSpecialAutoWalk respEnableSpecialAutoWalk = new RespEnableSpecialAutoWalk();
        MessagePusher.pushMessage(role, respEnableSpecialAutoWalk);


        RespSpecialServer respSpecialServer = new RespSpecialServer();
        MessagePusher.pushMessage(role, respSpecialServer);

        RespBaxianLeftTimes respBaxianLeftTimes = new RespBaxianLeftTimes();
        MessagePusher.pushMessage(role, respBaxianLeftTimes);

        RespNewLotteryOpen respNewLotteryOpen = new RespNewLotteryOpen();
        MessagePusher.pushMessage(role, respNewLotteryOpen);

        RespShuadaoUsePointStatus respShuadaoUsePointStatus = new RespShuadaoUsePointStatus();
        MessagePusher.pushMessage(role, respShuadaoUsePointStatus);

        RespUpdateMoveSpeed respUpdateMoveSpeed = new RespUpdateMoveSpeed();
        respUpdateMoveSpeed.setRoleId(role.getRoleId());
        MessagePusher.pushMessage(role, respUpdateMoveSpeed);

        RespLBS_FriendGidList respLBSFriendGidList = new RespLBS_FriendGidList();
        MessagePusher.pushMessage(role, respLBSFriendGidList);

        RespINN_EnterWorld respINNEnterWorld = new RespINN_EnterWorld();
        MessagePusher.pushMessage(role, respINNEnterWorld);

        RespTradingAuctionBidGids respTradingAuctionBidGids = new RespTradingAuctionBidGids();
        MessagePusher.pushMessage(role, respTradingAuctionBidGids);

        RespTradingFavoriteGids respTradingFavoriteGids = new RespTradingFavoriteGids();
        MessagePusher.pushMessage(role, respTradingFavoriteGids);

        RespTradingGoodMine respTradingGoodMine = new RespTradingGoodMine();
        MessagePusher.pushMessage(role, respTradingGoodMine);

        RespLD_LifeDeathId respLDLifeDeathId = new RespLD_LifeDeathId();
        MessagePusher.pushMessage(role, respLDLifeDeathId);


        RespSetPushSetting respSetPushSetting = new RespSetPushSetting();
        respSetPushSetting.setValue("1001101111");//1001101111
        MessagePusher.pushMessage(role, respSetPushSetting);
        //////////////////////////
        RespRechargeInfo respRechargeInfo = new RespRechargeInfo();
        MessagePusher.pushMessage(role, respRechargeInfo);

    }
    //增加成就积分
    public void addAchieveScore(Role role,String id){
        AchieveImgInfos achieveImgInfos = role.getExtendBox().getAchieveImgInfos();
        if(achieveImgInfos == null){
            achieveImgInfos = new AchieveImgInfos();
            role.getExtendBox().setAchieveImgInfos(achieveImgInfos);
        }
        HashMap<String,Integer> achieveMap = achieveImgInfos.getAchieveMap();
        if(achieveMap.containsKey(id)){
            return;
        }
        AchieveSet achieveSet = DataCache.ACHIEVE_DATA.get(id);
        achieveImgInfos.setTotalScore(achieveImgInfos.getTotalScore()+achieveSet.getScore());
        String type = achieveSet.getType().substring(0,1);
        if(type.equals(AchieveScoreType.lvScore)){
            achieveImgInfos.setLvScore(achieveImgInfos.getLvScore()+achieveSet.getScore());
        }else if(type.equals(AchieveScoreType.firendScore)){
            achieveImgInfos.setFirendScore(achieveImgInfos.getFirendScore()+achieveSet.getScore());
        }else if(type.equals(AchieveScoreType.equipScore)){
            achieveImgInfos.setEquipScore(achieveImgInfos.getEquipScore()+achieveSet.getScore());
        }else if(type.equals(AchieveScoreType.roleScore)){
            achieveImgInfos.setRoleScore(achieveImgInfos.getRoleScore()+achieveSet.getScore());
        }else if(type.equals(AchieveScoreType.taskScore)){
            achieveImgInfos.setTaskScore(achieveImgInfos.getTaskScore()+achieveSet.getScore());
        }else if(type.equals(AchieveScoreType.extScore)){
            achieveImgInfos.setExtScore(achieveImgInfos.getExtScore()+achieveSet.getScore());
        }
        int currTime = new Long(new Date().getTime() / 1000).intValue();
        achieveMap.put(id,currTime);
        //发送完成成就包
        RespAchieveFinished respAchieveFinished = new RespAchieveFinished();
        respAchieveFinished.setAchieve_id(Integer.parseInt(id));
        respAchieveFinished.setAchieve_name(achieveSet.getTitle());
        MessagePusher.pushMessage(role, respAchieveFinished);
    }

    //结婚
    public void recordPositionJH(Role role, int x, int y, int dir, int mapId) {
        role.setPos(x, y, dir, mapId);
    }
//    // add tao 跟宠飞
//    public void genchongfei(Role role) {
//        RoleEquip roleEquip = role.getFasionRoleEquip("followPet");
//        if (roleEquip == null)
//            return;
//        this.log.error("{}换地图过程中的followPet为{}", role.getName(), roleEquip.getName());
////        SpringUtils.getBean(FasionService.class).equipFasion(SessionUtils.getSession(role.getRoleId()), roleEquip.getName());
//        SpringUtils.getBean(FasionService.class).unEquipCustomFasion(role, (short) 37, false);
//        SpringUtils.getBean(FasionService.class).broadcastFollowPet(role, roleEquip);
//    }
//    // add:e
}